package dev.lions.events;

import dev.lions.exceptions.EventProcessingException;
import dev.lions.utils.CacheService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ApplicationScoped
public class ProjectEventHandler {

  @Inject
  private CacheService cacheService;

  @Inject
  private SearchIndexService searchIndexService;

  public void onProjectUpdate(@Observes ProjectUpdateEvent event) {
    try {
      // Invalidation du cache
      cacheService.invalidateProjectCache(event.getProjectId());

      // Mise à jour de l'index de recherche
      if ("CREATE".equals(event.getAction()) || "UPDATE".equals(event.getAction())) {
        searchIndexService.indexProject(event.getProjectId());
      } else if ("DELETE".equals(event.getAction())) {
        searchIndexService.removeFromIndex(event.getProjectId());
      }

      log.info("Project event processed successfully. Action: {}, Project ID: {}",
               event.getAction(), event.getProjectId());

    } catch (Exception e) {
      log.error("Error processing project event", e);
      throw new EventProcessingException("Failed to process project event", e);
    }
  }
}
