package com.astalange.web.controller;

import com.astalange.core.entity.Adherent;
import com.astalange.core.repository.AdherentRepository;
import com.astalange.core.repository.LicenceRepository;
import com.astalange.core.repository.PaiementRepository;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.util.List;

@Controller
public class HomeController {

    private final AdherentRepository adherentRepository;
    private final LicenceRepository licenceRepository;
    private final PaiementRepository paiementRepository;

    public HomeController(AdherentRepository adherentRepository, LicenceRepository licenceRepository, PaiementRepository paiementRepository) {
        this.adherentRepository = adherentRepository;
        this.licenceRepository = licenceRepository;
        this.paiementRepository = paiementRepository;
    }

    @GetMapping("/")
    public String home(Model model, Authentication authentication) {
        if (authentication != null) {
            model.addAttribute("username", authentication.getName());
        }

        long totalAdherents = adherentRepository.count();
        long licencesBrouillon = licenceRepository.countByEtat("Brouillon");
        long licencesValidees = licenceRepository.countByEtat("Validée");
        long licencesPayees = licenceRepository.countByEtat("Payée");
        
        BigDecimal totalEncaisse = paiementRepository.sumMontant();
        if (totalEncaisse == null) totalEncaisse = BigDecimal.ZERO;
        
        List<com.astalange.core.entity.Licence> allLicences = licenceRepository.findAll();
        BigDecimal totalAttendu = allLicences.stream()
                .map(com.astalange.core.entity.Licence::getPrixTotal)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        BigDecimal resteARecouvrer = totalAttendu.subtract(totalEncaisse);
        if (resteARecouvrer.compareTo(BigDecimal.ZERO) < 0) resteARecouvrer = BigDecimal.ZERO;

        List<Adherent> derniersInscrits = adherentRepository.findTop5ByOrderByIdDesc();

        model.addAttribute("totalAdherents", totalAdherents);
        model.addAttribute("licencesBrouillon", licencesBrouillon);
        model.addAttribute("licencesActives", licencesValidees + licencesPayees);
        model.addAttribute("totalEncaisse", totalEncaisse);
        model.addAttribute("resteARecouvrer", resteARecouvrer);
        model.addAttribute("derniersInscrits", derniersInscrits);

        return "index";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }
}
