package dev.lions.unionflow.server.resource.mutuelle;

import dev.lions.unionflow.server.security.RequiresModule;
import dev.lions.unionflow.server.service.mutuelle.ReleveComptePdfService;
import jakarta.annotation.security.RolesAllowed;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.ResponseBuilder;

import java.time.LocalDate;
import java.util.UUID;

/**
 * Relevés de compte en PDF.
 * - GET /api/v1/releves/epargne/{compteId}     → relevé épargne
 * - GET /api/v1/releves/parts-sociales/{compteId} → relevé parts sociales
 */
@Path("/api/v1/releves")
@RequiresModule("EPARGNE")
public class ReleveCompteResource {

    @Inject ReleveComptePdfService releveService;

    @GET
    @Path("/epargne/{compteId}")
    @Produces("application/pdf")
    @RolesAllowed({"ADMIN", "SUPER_ADMIN", "ADMIN_ORGANISATION", "MUTUELLE_RESP", "MEMBRE", "USER"})
    public Response releveEpargne(
            @PathParam("compteId") UUID compteId,
            @QueryParam("dateDebut") String dateDebutStr,
            @QueryParam("dateFin") String dateFinStr) {

        LocalDate dateDebut = parseDate(dateDebutStr);
        LocalDate dateFin = parseDate(dateFinStr);
        byte[] pdf = releveService.genererReleveEpargne(compteId, dateDebut, dateFin);

        ResponseBuilder rb = Response.ok(pdf);
        rb.header("Content-Disposition",
                "attachment; filename=\"releve-epargne-" + compteId + ".pdf\"");
        rb.header("Content-Type", MediaType.valueOf("application/pdf"));
        return rb.build();
    }

    @GET
    @Path("/parts-sociales/{compteId}")
    @Produces("application/pdf")
    @RolesAllowed({"ADMIN", "SUPER_ADMIN", "ADMIN_ORGANISATION", "MUTUELLE_RESP", "MEMBRE", "USER"})
    public Response releveParts(
            @PathParam("compteId") UUID compteId,
            @QueryParam("dateDebut") String dateDebutStr,
            @QueryParam("dateFin") String dateFinStr) {

        LocalDate dateDebut = parseDate(dateDebutStr);
        LocalDate dateFin = parseDate(dateFinStr);
        byte[] pdf = releveService.genererReleveParts(compteId, dateDebut, dateFin);

        ResponseBuilder rb = Response.ok(pdf);
        rb.header("Content-Disposition",
                "attachment; filename=\"releve-parts-" + compteId + ".pdf\"");
        rb.header("Content-Type", MediaType.valueOf("application/pdf"));
        return rb.build();
    }

    private LocalDate parseDate(String s) {
        if (s == null || s.isBlank()) return null;
        try {
            return LocalDate.parse(s);
        } catch (Exception e) {
            throw new IllegalArgumentException("Format de date invalide. Utilisez YYYY-MM-DD. Valeur reçue: " + s);
        }
    }
}
