package dev.lions.unionflow.server.resource;

import dev.lions.unionflow.server.api.dto.logs.request.LogSearchRequest;
import dev.lions.unionflow.server.api.dto.logs.request.UpdateAlertConfigRequest;
import dev.lions.unionflow.server.api.dto.logs.response.AlertConfigResponse;
import dev.lions.unionflow.server.api.dto.logs.response.SystemAlertResponse;
import dev.lions.unionflow.server.api.dto.logs.response.SystemLogResponse;
import dev.lions.unionflow.server.api.dto.logs.response.SystemMetricsResponse;
import dev.lions.unionflow.server.service.LogsMonitoringService;
import jakarta.annotation.security.RolesAllowed;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;

import java.util.List;
import java.util.UUID;

/**
 * REST Resource pour la gestion des logs et du monitoring système
 */
@Slf4j
@Path("/api")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Tag(name = "Logs & Monitoring", description = "Gestion des logs système et monitoring")
public class LogsMonitoringResource {

    @Inject
    LogsMonitoringService logsMonitoringService;

    /**
     * Rechercher dans les logs système
     */
    @POST
    @Path("/logs/search")
    @RolesAllowed({"SUPER_ADMIN", "ADMIN", "MODERATEUR"})
    @Operation(summary = "Rechercher dans les logs système", description = "Recherche avec filtres (niveau, source, texte, dates)")
    public List<SystemLogResponse> searchLogs(@Valid LogSearchRequest request) {
        log.info("POST /api/logs/search - level={}, source={}", request.getLevel(), request.getSource());
        return logsMonitoringService.searchLogs(request);
    }

    /**
     * Exporter les logs (simplifié)
     */
    @GET
    @Path("/logs/export")
    @RolesAllowed({"SUPER_ADMIN", "ADMIN"})
    @Produces("text/csv")
    @Operation(summary = "Exporter les logs en CSV")
    public Response exportLogs(
            @QueryParam("level") String level,
            @QueryParam("source") String source,
            @QueryParam("timeRange") String timeRange
    ) {
        log.info("GET /api/logs/export");

        // Dans une vraie implémentation, on générerait un vrai CSV
        LogSearchRequest request = LogSearchRequest.builder()
                .level(level)
                .source(source)
                .timeRange(timeRange)
                .build();

        List<SystemLogResponse> logs = logsMonitoringService.searchLogs(request);

        // Génération simplifiée du CSV
        StringBuilder csv = new StringBuilder();
        csv.append("Timestamp,Level,Source,Message,Details\n");
        logs.forEach(log -> csv.append(String.format("%s,%s,%s,\"%s\",\"%s\"\n",
                log.getTimestamp(),
                log.getLevel(),
                log.getSource(),
                log.getMessage().replace("\"", "\"\""),
                log.getDetails() != null ? log.getDetails().replace("\"", "\"\"") : ""
        )));

        return Response.ok(csv.toString())
                .header("Content-Disposition", "attachment; filename=\"logs-export.csv\"")
                .build();
    }

    /**
     * Récupérer les métriques système en temps réel
     */
    @GET
    @Path("/monitoring/metrics")
    @RolesAllowed({"SUPER_ADMIN", "ADMIN", "MODERATEUR"})
    @Operation(summary = "Récupérer les métriques système en temps réel")
    public SystemMetricsResponse getSystemMetrics() {
        log.debug("GET /api/monitoring/metrics");
        return logsMonitoringService.getSystemMetrics();
    }

    /**
     * Récupérer toutes les alertes actives
     */
    @GET
    @Path("/alerts")
    @RolesAllowed({"SUPER_ADMIN", "ADMIN", "MODERATEUR"})
    @Operation(summary = "Récupérer toutes les alertes actives")
    public List<SystemAlertResponse> getActiveAlerts() {
        log.info("GET /api/alerts");
        return logsMonitoringService.getActiveAlerts();
    }

    /**
     * Acquitter une alerte
     */
    @POST
    @Path("/alerts/{id}/acknowledge")
    @RolesAllowed({"SUPER_ADMIN", "ADMIN", "MODERATEUR"})
    @Operation(summary = "Acquitter une alerte")
    public Response acknowledgeAlert(@PathParam("id") UUID id) {
        log.info("POST /api/alerts/{}/acknowledge", id);
        logsMonitoringService.acknowledgeAlert(id);
        return Response.ok().entity(java.util.Map.of("message", "Alerte acquittée avec succès")).build();
    }

    /**
     * Récupérer la configuration des alertes
     */
    @GET
    @Path("/alerts/config")
    @RolesAllowed({"SUPER_ADMIN", "ADMIN", "MODERATEUR"})
    @Operation(summary = "Récupérer la configuration des alertes système")
    public AlertConfigResponse getAlertConfig() {
        log.info("GET /api/alerts/config");
        return logsMonitoringService.getAlertConfig();
    }

    /**
     * Mettre à jour la configuration des alertes
     */
    @PUT
    @Path("/alerts/config")
    @RolesAllowed({"SUPER_ADMIN", "ADMIN"})
    @Operation(summary = "Mettre à jour la configuration des alertes système")
    public AlertConfigResponse updateAlertConfig(@Valid UpdateAlertConfigRequest request) {
        log.info("PUT /api/alerts/config");
        return logsMonitoringService.updateAlertConfig(request);
    }
}
