package dev.lions.unionflow.server.resource;

import dev.lions.unionflow.server.security.AuditTrailService;
import dev.lions.unionflow.server.service.compliance.KpiShareTokenService;
import io.quarkus.security.Authenticated;
import jakarta.annotation.security.RolesAllowed;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import java.util.Map;
import java.util.UUID;

/**
 * Génération de liens KPI signés (Sprint 17) — admin uniquement.
 *
 * <p>Crée un token signé HMAC-SHA256 valide pendant {@code ttlSeconds} (défaut 7 jours)
 * permettant à une autorité externe de consulter les KPI agrégés sans login.
 *
 * @since 2026-04-25 (Sprint 17)
 */
@Path("/api/admin/kpi/share-link")
@Produces(MediaType.APPLICATION_JSON)
@Authenticated
public class KpiShareLinkResource {

  @Inject KpiShareTokenService tokenService;
  @Inject AuditTrailService auditTrail;

  @GET
  @Path("/{orgId}")
  @RolesAllowed({"ADMIN_ORGANISATION", "PRESIDENT", "COMPLIANCE_OFFICER", "SUPER_ADMIN"})
  public Map<String, Object> generer(
      @PathParam("orgId") UUID orgId,
      @QueryParam("ttlSeconds") Long ttlSeconds) {

    long ttl = ttlSeconds == null ? KpiShareTokenService.DEFAULT_TTL_SECONDS : ttlSeconds;
    String token = tokenService.generer(orgId, ttl);

    auditTrail.logSimple("KpiShareLink", orgId, "CREATE",
        "Lien KPI public généré (TTL " + ttl + "s)");

    return Map.of(
        "token", token,
        "ttlSeconds", ttl,
        "publicUrl", "/api/public/kpi?token=" + token,
        "publicWebPath", "/pages/public/kpi?token=" + token);
  }
}
