package ai.decompile.job.messaging;

import ai.decompile.job.model.enums.JobStatus;
import ai.decompile.job.model.repository.JobRepository;
import ai.decompile.job.service.handler.JobHandlerFactory;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Log4j2
@Component
@RequiredArgsConstructor
public class JobMessageListener {
  private final JobRepository jobRepository;
  private final JobHandlerFactory handlerFactory;

  @RabbitListener(queues = "${app.rabbitmq.queue}")
  @Transactional
  public void onMessage(String jobId) {
    var id = UUID.fromString(jobId);
    var job =
        jobRepository
            .findById(id)
            .orElseThrow(() -> new IllegalStateException("Job not found: " + id));

    if (job.getStatus() == JobStatus.CANCELED) {
      log.info("Job {} is canceled, skipping", id);
      return;
    }

    job.setStatus(JobStatus.STARTED);
    jobRepository.save(job);

    try {
      job.setStatus(JobStatus.IN_PROGRESS);
      jobRepository.save(job);

      var handler = handlerFactory.getHandler(job.getType());
      handler.process(job);

      jobRepository.save(job);
    } catch (Exception e) {
      log.error("Job {} failed: {}", id, e.getMessage(), e);
      job.setStatus(JobStatus.FAILED);
      job.setErrorMessage(e.getMessage());
      jobRepository.save(job);
    }
  }
}
