package infrastructure.adapter.input.rest;

import application.helper.ResponseHelper;
import application.port.input.IAppConfig;
import com.banesco.common.infraestructure.helpers.LoggerHelper;
import domain.dto.response.CustomerResponse;
import domain.entity.AppConfiguration;
import infrastructure.context.TraceIdContext;
import infrastructure.service.StatusDescriptionResolver;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
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.enums.ParameterIn;
import org.eclipse.microprofile.openapi.annotations.enums.SchemaType;
import org.eclipse.microprofile.openapi.annotations.media.Content;
import org.eclipse.microprofile.openapi.annotations.media.ExampleObject;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
import org.jboss.resteasy.reactive.RestPath;

@Slf4j
@Path("/customer")
@Produces(MediaType.APPLICATION_JSON)
public class AppConfigResource {

    // --- CASOS DE USO Y SERVICIOS ---
    private final IAppConfig appConfigUseCase;

    // --- DEPENDENCIAS ADICIONALES ---
    private final ResponseHelper responseHelper;
    private final TraceIdContext traceIdContext;

    public AppConfigResource(
            IAppConfig appConfigUseCase,
            ResponseHelper responseHelper,
            TraceIdContext traceIdContext,
            StatusDescriptionResolver statusDescriptionResolver
    ) {
        this.appConfigUseCase = appConfigUseCase;
        this.responseHelper = responseHelper;
        this.traceIdContext = traceIdContext;
    }

    @GET
    @Path("/config/{appName}")
    @Operation(
            summary = "Obtener Configuración de Aplicación",
            description = "Obtiene la configuración JSON completa para un 'appName' (appId) específico. Este endpoint se usa para testing o recarga manual."
    )
    @Parameter(
            name = "appName",
            in = ParameterIn.PATH,
            description = "El 'appName' (appId) que se usará para buscar la configuración.",
            required = true,
            schema = @Schema(type = SchemaType.STRING),
            example = "abc123"
    )
    @APIResponses(value = {
            @APIResponse(
                    responseCode = "200",
                    description = "Configuración encontrada.",
                    content = @Content(
                            mediaType = MediaType.APPLICATION_JSON,
                            schema = @Schema(implementation = AppConfiguration.class),
                            examples = {
                                    @ExampleObject(
                                            name = "Configuración encontrada",
                                            externalValue = "/openapi-examples/response/app-config.json"
                                    )
                            }
                    )
            ),
            @APIResponse(
                    responseCode = "400",
                    description = "Configuración no encontrada. El 'appName' no existe en la base de datos.",
                    content = @Content(
                            mediaType = MediaType.APPLICATION_JSON,
                            schema = @Schema(implementation = CustomerResponse.class),
                            examples = {
                                    @ExampleObject(
                                            name = "Configuración no encontrada",
                                            summary = "VRN_CONFIG_NOT_FOUND",
                                            externalValue = "/openapi-examples/response/config-not-found.json"
                                    )
                            }
                    )
            )
    })
    public Response getConfig(@RestPath String appName) {
        final var requestId = traceIdContext.getTraceId();

        try {
            var config = appConfigUseCase.execute(appName);
            log.info(LoggerHelper.buildInfoPrivateRequest(requestId, "Configuracion encontrada para appName: " + appName));
            log.info(LoggerHelper.buildInfoPrivateRequest(requestId, "Configuracion: " + config));

            return Response.ok(config).build();

        } catch (NotFoundException ex) {
            log.warn(LoggerHelper.buildError(requestId, "Configuracion no encontrada (VRN_CONFIG_NOT_FOUND) para appName: " + appName));
            return responseHelper.buildErrorResponse("VRN_CONFIG_NOT_FOUND", requestId);
        }
    }
}