package com.astalange.web.controller;

import com.astalange.core.entity.Adherent;
import com.astalange.core.repository.PreInscriptionRepository;
import com.astalange.core.service.PreInscriptionService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/admin/pre-inscriptions")
public class AdminPreInscriptionController {

    private final PreInscriptionRepository preInscriptionRepository;
    private final PreInscriptionService preInscriptionService;

    public AdminPreInscriptionController(PreInscriptionRepository preInscriptionRepository,
                                         PreInscriptionService preInscriptionService) {
        this.preInscriptionRepository = preInscriptionRepository;
        this.preInscriptionService = preInscriptionService;
    }

    @GetMapping
    public String listPreInscriptions(Model model) {
        model.addAttribute("preInscriptions", preInscriptionRepository.findByStatutTraiteFalseOrderByDateCreationDesc());
        return "preinscriptions/list";
    }

    @PostMapping("/{id}/valider")
    @ResponseBody
    public String valider(@PathVariable Long id, HttpServletResponse response) {
        Adherent adherent = preInscriptionService.validerPreInscription(id, null);
        response.setHeader("HX-Trigger", "refreshBadge");
        // En HTMX, on renvoie une ligne vide pour la faire disparaître, ou on redirige via HX-Redirect
        // Mais comme on veut aller sur la page de l'adhérent pour finaliser la licence :
        response.setHeader("HX-Redirect", "/adherents/" + adherent.getId() + "/edit");
        return "";
    }

    @PostMapping("/{id}/rejeter")
    @ResponseBody
    public String rejeter(@PathVariable Long id, HttpServletResponse response) {
        preInscriptionService.rejeterPreInscription(id);
        response.setHeader("HX-Trigger", "refreshBadge");
        return ""; // HTMX target la ligne avec outerHTML -> supprime la ligne
    }

    @GetMapping("/count")
    @ResponseBody
    public String countBadge() {
        long count = preInscriptionRepository.countByStatutTraiteFalse();
        if (count == 0) return "";
        return "<span class=\"bg-red-500 text-white rounded-full px-2 py-0.5 text-xs font-bold ml-2\">" + count + "</span>";
    }
}
