package dev.lions.events;

import dev.lions.exceptions.EventProcessingException;
import dev.lions.models.Contact;
import dev.lions.services.NotificationService;
import dev.lions.models.NotificationType;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;

/**
 * Gestionnaire des événements liés aux contacts. Traite les soumissions de formulaires de contact
 * et déclenche les actions appropriées.
 */
@Slf4j
@ApplicationScoped
public class ContactEventHandler {

  @Inject
  private NotificationService notificationService;

  public void onContactSubmission(@Observes ContactSubmissionEvent event) {
    try {
      Contact contact = event.getContact();
      processAnalytics(contact);
      sendNotifications(contact);

      log.info("Contact submission event processed successfully for contact ID: {}",
               contact.getId());

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

  private void processAnalytics(Contact contact) {
    Map<String, Object> properties = new HashMap<>();
    properties.put("subject", contact.getSubject());
    properties.put("hasCompany", contact.getCompany() != null);
    properties.put("submissionTime", contact.getSubmitDate());

    AnalyticsEvent analyticsEvent =
        AnalyticsEvent.builder().eventType("CONTACT_SUBMISSION").contactId(
                          String.valueOf(contact.getId()))
                      .properties(properties).build();

    analyticsEvent.trackContactSubmission();
  }

  private void sendNotifications(Contact contact) {
    notificationService.sendInternalNotification(NotificationType.NEW_CONTACT,
                                                 String.format("Nouveau message de %s : %s",
                                                               contact.getName(),
                                                               contact.getSubject()));
  }
}