package dev.lions.unionflow.server.resource;

import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;
import org.jboss.logging.Logger;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Resource REST pour les workflows financiers (stats et audits)
 *
 * @author UnionFlow Team
 * @version 1.0
 * @since 2026-03-16
 */
@Path("/api/finance")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Tag(name = "Finance - Workflow", description = "Statistiques et audits des workflows financiers")
public class FinanceWorkflowResource {

    private static final Logger LOG = Logger.getLogger(FinanceWorkflowResource.class);

    @GET
    @Path("/stats")
    @RolesAllowed({"ADMIN_ORGANISATION", "SUPER_ADMIN"})
    @Operation(summary = "Statistiques du workflow financier",
               description = "Retourne les statistiques globales du workflow financier")
    public Response getWorkflowStats(
            @QueryParam("organizationId") String organizationId,
            @QueryParam("startDate") String startDate,
            @QueryParam("endDate") String endDate) {
        LOG.infof("GET /api/finance/stats?organizationId=%s", organizationId);

        Map<String, Object> stats = new HashMap<>();
        stats.put("totalApprovals", 0);
        stats.put("pendingApprovals", 0);
        stats.put("approvedCount", 0);
        stats.put("rejectedCount", 0);
        stats.put("totalBudgets", 0);
        stats.put("activeBudgets", 0);
        stats.put("averageApprovalTime", "0 hours");
        stats.put("period", Map.of(
            "startDate", startDate != null ? startDate : LocalDateTime.now().minusMonths(1).toString(),
            "endDate", endDate != null ? endDate : LocalDateTime.now().toString()
        ));
        return Response.ok(stats).build();
    }

    @GET
    @Path("/audit-logs")
    @RolesAllowed({"ADMIN_ORGANISATION", "SUPER_ADMIN"})
    @Operation(summary = "Récupère les logs d'audit financier",
               description = "Liste les logs d'audit avec filtres optionnels")
    public Response getAuditLogs(
            @QueryParam("organizationId") String organizationId,
            @QueryParam("startDate") String startDate,
            @QueryParam("endDate") String endDate,
            @QueryParam("operation") String operation,
            @QueryParam("entityType") String entityType,
            @QueryParam("severity") String severity,
            @QueryParam("limit") @DefaultValue("100") int limit) {
        LOG.infof("GET /api/finance/audit-logs?organizationId=%s&limit=%d", organizationId, limit);

        // Retourne une liste vide pour l'instant - à implémenter plus tard avec vraie persistence
        return Response.ok(new ArrayList<>()).build();
    }

    @GET
    @Path("/audit-logs/anomalies")
    @RolesAllowed({"ADMIN_ORGANISATION", "SUPER_ADMIN"})
    @Operation(summary = "Récupère les anomalies financières détectées",
               description = "Liste les anomalies et transactions suspectes")
    public Response getAnomalies(
            @QueryParam("organizationId") String organizationId,
            @QueryParam("startDate") String startDate,
            @QueryParam("endDate") String endDate) {
        LOG.infof("GET /api/finance/audit-logs/anomalies?organizationId=%s", organizationId);

        // Retourne une liste vide pour l'instant - à implémenter plus tard
        return Response.ok(new ArrayList<>()).build();
    }

    @POST
    @Path("/audit-logs/export")
    @RolesAllowed({"ADMIN_ORGANISATION", "SUPER_ADMIN"})
    @Operation(summary = "Exporte les logs d'audit",
               description = "Génère un export des logs d'audit au format spécifié (CSV/PDF)")
    public Response exportAuditLogs(Map<String, Object> request) {
        String organizationId = (String) request.get("organizationId");
        String format = (String) request.getOrDefault("format", "csv");

        LOG.infof("POST /api/finance/audit-logs/export - format: %s", format);

        // Pour l'instant, retourne un URL fictif - à implémenter plus tard
        String exportUrl = "/api/finance/exports/" + UUID.randomUUID() + "." + format;

        Map<String, Object> response = new HashMap<>();
        response.put("exportUrl", exportUrl);
        response.put("format", format);
        response.put("status", "generated");
        response.put("expiresAt", LocalDateTime.now().plusHours(24).toString());

        return Response.ok(response).build();
    }
}
