package dev.lions.unionflow.server.resource;

import dev.lions.unionflow.server.api.dto.reference.request.CreateTypeReferenceRequest;
import dev.lions.unionflow.server.api.dto.reference.request.UpdateTypeReferenceRequest;
import dev.lions.unionflow.server.api.dto.reference.response.TypeReferenceResponse;
import dev.lions.unionflow.server.service.TypeReferenceService;
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.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
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.Map;
import java.util.UUID;

import io.quarkus.security.identity.SecurityIdentity;

/**
 * Alias REST pour le catalogue des types d'organisation.
 * Le client appelle /api/references/types-organisation (GET liste, POST créer,
 * PUT /{id} modifier, DELETE /{id} désactiver). Délègue au service des références
 * avec le domaine TYPE_ORGANISATION.
 *
 * @author UnionFlow Team
 */
@Path("/api/references/types-organisation")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@RolesAllowed({ "SUPER_ADMIN", "ADMIN", "ADMIN_ORGANISATION", "MEMBRE", "USER" })
public class TypeOrganisationReferenceResource {

    private static final String DOMAINE_TYPE_ORGANISATION = "TYPE_ORGANISATION";

    @Inject
    TypeReferenceService typeReferenceService;

    @Inject
    SecurityIdentity securityIdentity;

    @GET
    public Response list(
            @QueryParam("onlyActifs") @DefaultValue("true") boolean onlyActifs) {
        List<TypeReferenceResponse> list = typeReferenceService.listerParDomaine(
                DOMAINE_TYPE_ORGANISATION, null);
        return Response.ok(list).build();
    }

    @POST
    @RolesAllowed({ "SUPER_ADMIN", "ADMIN" })
    public Response create(@Valid CreateTypeReferenceRequest request) {
        CreateTypeReferenceRequest withDomaine = CreateTypeReferenceRequest.builder()
                .domaine(DOMAINE_TYPE_ORGANISATION)
                .code(request.code())
                .libelle(request.libelle())
                .description(request.description())
                .icone(request.icone())
                .couleur(request.couleur())
                .severity(request.severity())
                .ordreAffichage(request.ordreAffichage())
                .estDefaut(request.estDefaut())
                .estSysteme(request.estSysteme())
                .organisationId(request.organisationId())
                .categorie(request.categorie())
                .modulesRequis(request.modulesRequis())
                .build();
        try {
            TypeReferenceResponse created = typeReferenceService.creer(withDomaine);
            return Response.status(Response.Status.CREATED).entity(created).build();
        } catch (IllegalArgumentException e) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity(Map.of("error", e.getMessage()))
                    .build();
        }
    }

    @PUT
    @Path("/{id}")
    @RolesAllowed({ "SUPER_ADMIN", "ADMIN" })
    public Response update(@PathParam("id") UUID id, @Valid UpdateTypeReferenceRequest request) {
        try {
            TypeReferenceResponse updated = typeReferenceService.modifier(id, request);
            return Response.ok(updated).build();
        } catch (IllegalArgumentException e) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity(Map.of("error", e.getMessage()))
                    .build();
        }
    }

    @DELETE
    @Path("/{id}")
    @RolesAllowed({ "SUPER_ADMIN", "ADMIN" })
    public Response supprimer(@PathParam("id") UUID id) {
        try {
            if (securityIdentity.hasRole("SUPER_ADMIN")) {
                typeReferenceService.supprimerPourSuperAdmin(id);
            } else {
                typeReferenceService.supprimer(id);
            }
            return Response.noContent().build();
        } catch (IllegalArgumentException e) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity(Map.of("error", e.getMessage()))
                    .build();
        }
    }
}
