package ai.decompile.job.service;

import ai.decompile.analysis.event.StaticAnalysisCompletedEvent;
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.boot.autoconfigure.condition.ConditionalOnProperty;
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
@ConditionalOnProperty(name = "app.ai.enabled", havingValue = "true", matchIfMissing = true)
public class EmbeddingEventSubscriber {
  private final JobRepository jobRepository;
  private final JobMessagePublisher jobMessagePublisher;

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

    var job = createJob(event);
    log.info(
        ">>> EmbeddingEventSubscriber: Saved GENERATE_EMBEDDINGS job {} for binary {}",
        job.getId(),
        event.binaryId());
    jobMessagePublisher.publish(job.getId());
  }

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