package ai.decompile.job.service;

import ai.decompile.analysis.event.StaticAnalysisRequestedEvent;
import ai.decompile.job.messaging.JobMessagePublisher;
import ai.decompile.job.model.entity.Job;
import ai.decompile.job.model.enums.JobStatus;
import ai.decompile.job.model.enums.JobType;
import ai.decompile.job.model.repository.JobRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.modulith.events.ApplicationModuleListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Log4j2
@Component
@RequiredArgsConstructor
public class StaticAnalysisEventSubscriber {
  private final JobRepository jobRepository;
  private final JobMessagePublisher jobMessagePublisher;

  @ApplicationModuleListener
  public void on(StaticAnalysisRequestedEvent event) {
    log.info(
        ">>> StaticAnalysisEventSubscriber: Received StaticAnalysisRequestedEvent binary={} engine={}",
        event.binaryId(),
        event.engineName());

    var job = createJob(event);

    log.info(
        ">>> StaticAnalysisEventSubscriber: Saved job {} - publishing to RabbitMQ", job.getId());
    jobMessagePublisher.publish(job.getId());
    log.info(">>> StaticAnalysisEventSubscriber: Published job {} to RabbitMQ", job.getId());
  }

  @Transactional(propagation = Propagation.REQUIRES_NEW)
  Job createJob(StaticAnalysisRequestedEvent event) {
    return jobRepository.save(
        Job.builder()
            .type(JobType.STATIC_ANALYSIS)
            .status(JobStatus.ENQUEUED)
            .projectId(event.projectId())
            .binaryId(event.binaryId())
            .payload("{\"engine\":\"" + event.engineName() + "\"}")
            .retryCount(0)
            .build());
  }
}
