package com.petshop.backend.event;

import com.petshop.backend.repository.AdoptionRepository;
import com.petshop.backend.repository.AppointmentRepository;
import com.petshop.backend.repository.SaleRepository;
import com.petshop.backend.service.EmailService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

@Component
public class EmailEventListener {

    private final AdoptionRepository adoptionRepository;
    private final AppointmentRepository appointmentRepository;
    private final SaleRepository saleRepository;
    private final EmailService emailService;

    public EmailEventListener(AdoptionRepository adoptionRepository, AppointmentRepository appointmentRepository, SaleRepository saleRepository, EmailService emailService) {
        this.adoptionRepository = adoptionRepository;
        this.appointmentRepository = appointmentRepository;
        this.saleRepository = saleRepository;
        this.emailService = emailService;
    }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void onAdoptionConfirmed(AdoptionConfirmedEvent event) {
        adoptionRepository.findById(event.adoptionId())
                .ifPresent(emailService::sendAdoptionConfirmation);
    }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void onAdoptionReminder(AdoptionReminderEvent event) {
        adoptionRepository.findById(event.adoptionId())
                .ifPresent(emailService::sendAdoptionReminder);
    }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void onAppointmentConfirmed(AppointmentConfirmedEvent event) {
        appointmentRepository.findById(event.appointmentId())
                .ifPresent(emailService::sendAppointmentConfirmation);
    }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void onAppointmentReminder(AppointmentReminderEvent event) {
        appointmentRepository.findById(event.appointmentId())
                .ifPresent(emailService::sendAppointmentReminder);
    }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void onSaleReceipt(SaleReceiptEvent event) {
        saleRepository.findById(event.saleId())
                .ifPresent(emailService::sendPurchaseReceipt);
    }
}
