package dev.lions.unionflow.server.resource;

import dev.lions.unionflow.server.api.dto.delegation.request.CreateRoleDelegationRequest;
import dev.lions.unionflow.server.api.dto.delegation.response.RoleDelegationResponse;
import dev.lions.unionflow.server.service.delegation.RoleDelegationService;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.security.Authenticated;
import jakarta.annotation.security.RolesAllowed;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
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 jakarta.ws.rs.core.Response;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * Endpoints REST des délégations de rôle (Sprint 10 — service Sprint 2).
 *
 * <p>La Resource ne fait que mapper HTTP ↔ {@link RoleDelegationService}. La
 * logique SoD, validation de dates, audit trail est dans le Service.
 *
 * <p>Le set des rôles du délégataire est passé via {@code SecurityIdentity} pour
 * vérification SoD : le client web/mobile fournit cette info via header (à terme).
 *
 * @since 2026-04-25 (Sprint 10)
 */
@Path("/api/role-delegations")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Authenticated
public class RoleDelegationResource {

  @Inject RoleDelegationService service;
  @Inject SecurityIdentity securityIdentity;

  @GET
  @Path("/organisation/{orgId}")
  @RolesAllowed({"ADMIN_ORGANISATION", "PRESIDENT", "SUPER_ADMIN", "COMPLIANCE_OFFICER"})
  public List<RoleDelegationResponse> listerParOrganisation(@PathParam("orgId") UUID orgId) {
    return service.listerParOrganisation(orgId);
  }

  @POST
  @RolesAllowed({"ADMIN_ORGANISATION", "PRESIDENT", "SUPER_ADMIN"})
  public Response creer(
      @Valid CreateRoleDelegationRequest request,
      @QueryParam("rolesDelegataire") String rolesDelegataireCsv) {
    Set<String> rolesDelegataire = parseRoles(rolesDelegataireCsv);
    RoleDelegationResponse created = service.creerDepuisRequest(request, rolesDelegataire);
    return Response.status(Response.Status.CREATED).entity(created).build();
  }

  @DELETE
  @Path("/{id}")
  @RolesAllowed({"ADMIN_ORGANISATION", "PRESIDENT", "SUPER_ADMIN"})
  public RoleDelegationResponse revoquer(@PathParam("id") UUID id) {
    return service.revoquerEtRetourner(id);
  }

  private Set<String> parseRoles(String csv) {
    if (csv == null || csv.isBlank()) return Set.of();
    return Set.of(csv.split(","));
  }
}
