package com.astalange.core.service;

import com.astalange.core.entity.Adherent;
import com.astalange.core.entity.Licence;
import com.astalange.core.entity.PreInscription;
import com.astalange.core.repository.AdherentRepository;
import com.astalange.core.repository.LicenceRepository;
import com.astalange.core.repository.PreInscriptionRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PreInscriptionService {

    private final PreInscriptionRepository preInscriptionRepository;
    private final AdherentRepository adherentRepository;
    private final LicenceRepository licenceRepository;

    public PreInscriptionService(PreInscriptionRepository preInscriptionRepository,
                                 AdherentRepository adherentRepository,
                                 LicenceRepository licenceRepository) {
        this.preInscriptionRepository = preInscriptionRepository;
        this.adherentRepository = adherentRepository;
        this.licenceRepository = licenceRepository;
    }

    @Transactional
    public Adherent validerPreInscription(Long preInscriptionId, Long categorieId) {
        PreInscription pre = preInscriptionRepository.findById(preInscriptionId)
                .orElseThrow(() -> new IllegalArgumentException("Pré-inscription introuvable"));

        if (pre.getStatutTraite()) {
            throw new IllegalStateException("Cette pré-inscription a déjà été traitée");
        }

        // Créer l'adhérent
        Adherent adherent = new Adherent();
        adherent.setNom(pre.getNom().toUpperCase());
        adherent.setPrenom(pre.getPrenom());
        adherent.setDateNaissance(pre.getDateNaissance());
        adherent.setLieuNaissanceVille(pre.getLieuNaissanceVille());
        adherent.setLieuNaissancePays(pre.getLieuNaissancePays());
        adherent.setNationalite(pre.getNationalite());
        adherent.setEmail(pre.getEmail());
        adherent.setRepresentantLegal(pre.getRepresentantLegal());
        // Par défaut
        adherent.setSexe("MASCULIN");
        adherent.setTypeMaillot("JOUEUR");
        adherent.setResidentTalange(false);
        
        adherent = adherentRepository.save(adherent);

        pre.setStatutTraite(true);
        preInscriptionRepository.save(pre);

        return adherent;
    }

    @Transactional
    public void rejeterPreInscription(Long preInscriptionId) {
        PreInscription pre = preInscriptionRepository.findById(preInscriptionId)
                .orElseThrow(() -> new IllegalArgumentException("Pré-inscription introuvable"));
        
        pre.setStatutTraite(true);
        preInscriptionRepository.save(pre);
    }
}
