package com.banesco.module.service_order_status_control.infrastructure.resource;

import com.banesco.common.domain.model.ApiResponse;
import com.banesco.common.domain.model.StatusResponse;
import com.banesco.module.service_order_status_control.application.usecase.ServiceOrderStatusControlUseCase;
import com.banesco.module.service_order_status_control.domain.dto.request.ServiceOrderStatusControlRequest;
import com.banesco.module.service_order_status_control.domain.dto.response.ServiceOrderStatusControlResponse;
import jakarta.inject.Inject;
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.media.Content;
import org.eclipse.microprofile.openapi.annotations.media.ExampleObject;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import org.eclipse.microprofile.openapi.annotations.media.SchemaProperty;
import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;

@Slf4j
@Path("/service-order-status-control")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ServiceOrderStatusControlResource {

    private final ServiceOrderStatusControlUseCase useCase;

    @Inject
    public ServiceOrderStatusControlResource(
        ServiceOrderStatusControlUseCase useCase
    ) {
        this.useCase = useCase;
    }

    @PATCH
    @Path("/control")
    @Operation(
        summary = "Cambia el estatus del servicio",
        description = "Envía el nuevo estatus del servicio"
    )
    @APIResponses(value = {
        @APIResponse(
            responseCode = "200",
            description = "Operacion exitosa",
            content = @Content(
                mediaType = MediaType.APPLICATION_JSON,
                schema = @Schema(
                    implementation = ApiResponse.class,
                    properties = {
                        @SchemaProperty(
                            name = "data",
                            oneOf = {ServiceOrderStatusControlResponse.class}
                        ),
                        @SchemaProperty(
                            name = "statusResponse",
                            implementation = StatusResponse.class
                        )
                    }
                ),
                examples = @ExampleObject(
                    name = "Ejemplo exitoso",
                    value = """
                    {
                      "data": {
                        "servicingOrderWorkTaskResult": {
                            "task": "A"
                        },
                        "transaction": {
                            "transactionIdentification": {
                                "identifierValue": "1966"
                            },
                            "transactionType": "0",
                            "transactionConsecutive": "0000",
                            "transactionDescription": "Activacion y Desactivacion TDD cuenta verde ME",
                            "event": {
                                "eventIdentification": {
                                    "identifierValue": "12345678901304"
                                },
                                "eventSource": "AS400",
                                "eventType": "Simple",
                                "eventStatus": "1232",
                                "eventDescription": "1"
                            },
                            "instruction": [
                                {
                                    "instructionIdentifier": {
                                        "instructionIdentification": {
                                            "identifierValue": "BAN1738A01"
                                        }
                                    },
                                    "instructionDescription": "1232"
                                }
                            ]
                        }
                      },
                      "statusResponse": {
                        "statusCode": "200",
                        "message": "Operacion exitosa"
                      }
                    }
                    """
                )
            )
        ),
        @APIResponse(
            responseCode = "400",
            description = "Error en formato o campo requerido",
            content = @Content(
                mediaType = MediaType.APPLICATION_JSON,
                schema = @Schema(
                    implementation = ApiResponse.class,
                    properties = {
                        @SchemaProperty(
                            name = "data",
                            oneOf = {ServiceOrderStatusControlResponse.class}
                        ),
                        @SchemaProperty(
                            name = "statusResponse",
                            implementation = StatusResponse.class
                        )
                    }
                ),
                examples = {
                    @ExampleObject(
                        name = "Error VDE01 - Campo obligatorio",
                        value = """
                        {
                          "data": null,
                          "statusResponse": {
                            "statusCode": "VDE01",
                            "message": "El campo document.documentName es obligatorio"
                          }
                        }
                        """
                    ),
                    @ExampleObject(
                        name = "Error VDE02 - Valor no permitido",
                        value = """
                        {
                          "data": null,
                          "statusResponse": {
                            "statusCode": "VDE02",
                            "message": "El valor 'XYZ' no es permitido para el campo channelCode. Valores permitidos: BOLE"
                          }
                        }
                        """
                    )
                }
            )
        ),
        @APIResponse(
            responseCode = "401",
            description = "No autorizado",
            content = @Content(
                mediaType = MediaType.APPLICATION_JSON,
                schema = @Schema(
                    implementation = ApiResponse.class,
                    properties = {
                        @SchemaProperty(
                            name = "data",
                            oneOf = {ServiceOrderStatusControlResponse.class}
                        ),
                        @SchemaProperty(
                            name = "statusResponse",
                            implementation = StatusResponse.class
                        )
                    }
                ),
                examples = {
                    @ExampleObject(
                        name = "Error VRN08 - Identificacion del fintechId no coincide",
                        value = """
                        {
                          "data": null,
                          "statusResponse": {
                            "statusCode": "VRN08",
                            "message": "El fintechId proporcionado no coincide con el registrado para este cliente"
                          }
                        }
                        """
                    )
                }
            )
        ),
        @APIResponse(
            responseCode = "503",
            description = "Servicio no disponible",
            content = @Content(
                mediaType = MediaType.APPLICATION_JSON,
                schema = @Schema(
                    implementation = ApiResponse.class,
                    properties = {
                        @SchemaProperty(
                            name = "data",
                            oneOf = {ServiceOrderStatusControlResponse.class}
                        ),
                        @SchemaProperty(
                            name = "statusResponse",
                            implementation = StatusResponse.class
                        )
                    }
                ),
                examples = {
                    @ExampleObject(
                        name = "Error VRN04 - Fuera de horario",
                        value = """
                        {
                          "data": null,
                          "statusResponse": {
                            "statusCode": "VRN04",
                            "message": "El servicio no esta disponible fuera del horario operativo"
                          }
                        }
                        """
                    ),
                    @ExampleObject(
                        name = "Error VDR13 - OSB no disponible",
                        value = """
                        {
                          "data": null,
                          "statusResponse": {
                            "statusCode": "VDR13",
                            "message": "El servicio OSB no esta disponible en este momento"
                          }
                        }
                        """
                    )
                }
            )
        )
    })
    public Response control(
        @HeaderParam("customerReferenceFintechId")
        @Parameter(description = "ID de la fintech", required = true, example = "provider-test")
        String customerReferenceFintechId,

        @HeaderParam("appId")
        @Parameter(description = "ID de la aplicacion", required = true, example = "DANIAPP")
        String appId,

        @RequestBody(
            description = "Request de la solicitud de cambio de estatus del servicio",
            content = @Content(
                mediaType = MediaType.APPLICATION_JSON,
                schema = @Schema(implementation = ServiceOrderStatusControlRequest.class),
                examples = @ExampleObject(
                    name = "Ejemplo de request",
                    value = """
                    {
                        "servicingOrderProcedureInstanceRecord": {
                            "workProduct": {
                                "productIdentification": {
                                    "identifierValue": "01"
                                },
                                "productReference": "01340000000000000000"
                            },
                            "customerReference": {
                                "partyIdentification": [
                                    {
                                        "partyIdentification": {
                                            "identifierValue": "204058941"
                                        }
                                    }
                                ]
                            },
                            "serviceOrderType": "CLT",
                            "serviceOrderDescription": "SDP",
                            "servicingOrderTask": {
                                "task": "A"
                            }
                        },
                        "device": {
                            "deviceType": "Mobile",
                            "deviceDescription": "Xiaomi Note 11 PRO",
                            "deviceIp": "127.0.0.1",
                            "deviceSessionReference": "12345678901304"
                        }
                    }
                    """
                )
            )
        )
        ServiceOrderStatusControlRequest request
    ) {
        log.info("Iniciando consulta para instruccion del cliente: {}", request.getClientId());

        return useCase.execute(ServiceOrderStatusControlRequest.fromResource(
            customerReferenceFintechId, appId, request
        ));
    }
}