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

import com.banesco.common.application.helper.MessageHelper;
import com.banesco.common.domain.exception.HttpStatusCodeException;
import com.banesco.common.domain.model.ApiResponse;
import com.banesco.common.domain.model.StatusResponse;
import com.banesco.module.instruction.domain.model.Instruction;
import com.banesco.module.service_order_payment_search.application.usecase.ServiceOrderPaymentSearchUseCase;
import com.banesco.module.service_order_payment_search.domain.dto.request.ServiceOrderPaymentSearchRequest;
import com.banesco.module.service_order_payment_search.domain.dto.response.ServiceOrderPaymentSearchResponse;
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.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;

import java.util.Objects;

@Slf4j
@Path("/bus-service-order-payment-search")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ServiceOrderPaymentSearchResource {

    private final ServiceOrderPaymentSearchUseCase useCase;
    private final MessageHelper messageHelper;

    @Inject
    public ServiceOrderPaymentSearchResource(
        MessageHelper messageHelper,
        ServiceOrderPaymentSearchUseCase useCase
    ) {
        this.messageHelper = messageHelper;
        this.useCase = useCase;
    }

    @GET
    @Path("/retrieve/{partyReferenceId}/{channelCode}/{signatureIdentifier}")
    @Operation(
        summary = "Recuperar informacion de la transaccion",
        description = "Consulta de una trasanccion de pago por id de archivo"
    )
    @APIResponses(value = {
        @APIResponse(
            responseCode = "200",
            description = "Operacion exitosa",
            content = @Content(
                mediaType = MediaType.APPLICATION_JSON,
                schema = @Schema(
                    implementation = ApiResponse.class,
                    properties = {
                        @SchemaProperty(
                            name = "data",
                            oneOf = {ServiceOrderPaymentSearchResponse.class}
                        ),
                        @SchemaProperty(
                            name = "statusResponse",
                            implementation = StatusResponse.class
                        )
                    }
                ),
                examples = @ExampleObject(
                    name = "Ejemplo exitoso",
                    value = """
                    {
                      "data": {
                        "servicingOrderProcedure": [
                            {
                                "document": {
                                    "documentName": "TESTING.CSV"
                                },
                                "transaction": {
                                    "transactionIdentification": {
                                        "identifierValue": "2"
                                    },
                                    "transactionStatus": {
                                        "statusType": "PENDING",
                                        "statusName": "PENDIENTE",
                                        "statusAccepted": 0,
                                        "statusRejected": 0,
                                        "statusExpired": 2
                                    },
                                    "transactionDate": [
                                        {
                                            "dateType": "EXECUTED_DATE",
                                            "date": "2026-01-05 14:35:45.0372395"
                                        }
                                    ],
                                    "transactionDetails": {
                                        "transactionQuantity": 1000
                                    }
                                }
                            },
                            {
                                "document": {
                                    "documentName": "TESTING.CSV"
                                },
                                "transaction": {
                                    "transactionIdentification": {
                                        "identifierValue": "3"
                                    },
                                    "transactionStatus": {
                                        "statusType": "IN_PROGRESS",
                                        "statusName": "EN CURSO",
                                        "statusAccepted": 0,
                                        "statusRejected": 0,
                                        "statusExpired": 5
                                    },
                                    "transactionDate": [
                                        {
                                            "dateType": "EXECUTED_DATE",
                                            "date": "2026-01-05 14:39:52.3840159"
                                        }
                                    ],
                                    "transactionDetails": {
                                        "transactionQuantity": 1000
                                    }
                                }
                            }
                        ]
                      },
                      "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 = {ServiceOrderPaymentSearchResponse.class}
                        ),
                        @SchemaProperty(
                            name = "statusResponse",
                            implementation = StatusResponse.class
                        )
                    }
                ),
                examples = {
                    @ExampleObject(
                        name = "Error VDE01 - Campo obligatorio",
                        value = """
                        {
                          "data": null,
                          "statusResponse": {
                            "statusCode": "VDE01",
                            "message": "El campo partyReferenceId 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: BOL, BOLE"
                          }
                        }
                        """
                    )
                }
            )
        ),
        @APIResponse(
            responseCode = "401",
            description = "No autorizado",
            content = @Content(
                mediaType = MediaType.APPLICATION_JSON,
                schema = @Schema(
                    implementation = ApiResponse.class,
                    properties = {
                        @SchemaProperty(
                            name = "data",
                            oneOf = {ServiceOrderPaymentSearchResponse.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 = {ServiceOrderPaymentSearchResponse.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 retrieve(
        @PathParam("partyReferenceId")
        @Parameter(description = "Identificacion del cliente", required = true, example = "J012341234")
        String partyReferenceId,

        @PathParam("channelCode")
        @Parameter(description = "Codigo del canal (BOL, BOLE)", required = true, example = "BOLE")
        String channelCode,

        @PathParam("signatureIdentifier")
        @Parameter(description = "Firma del archivo", required = true, example = "f8c226f844339c55bf898162c5d7de5d8116cee6028e1b357414dcc686b3ea85")
        String signatureIdentifier,

        @QueryParam("customerReferenceFintechId")
        @Parameter(description = "ID de la fintech", example = "pranical-test")
        String customerReferenceFintechId,

        @QueryParam("appId")
        @Parameter(description = "ID de la aplicacion", example = "DANIAPP")
        String appId
    ) {
        log.info("Iniciando consulta para instruccion de archivo id: {}", partyReferenceId);

        try {
            return Response.ok(useCase.execute(
                ServiceOrderPaymentSearchRequest.builder()
                    .customerReferenceFintechId(Objects.toString(customerReferenceFintechId, ""))
                    .appId(Objects.toString(appId, ""))
                    .procedureRequest(Instruction.fromResource(
                        partyReferenceId, channelCode, signatureIdentifier
                    ))
                    .build()
            )).build();
        } catch (HttpStatusCodeException e) {
            return messageHelper.handleException(e);
        } catch (Exception e) {
            return messageHelper.handleGenericException(e);
        }
    }
}