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

import com.banesco.common.application.helper.MessageHelper;
import com.banesco.common.domain.model.ApiResponse;
import com.banesco.common.domain.model.Device;
import com.banesco.common.domain.model.StatusResponse;
import com.banesco.module.instruction.domain.model.Instruction;
import com.banesco.module.service_issue_payment_status.application.usecase.ServiceIssuePaymentStatusUseCase;
import com.banesco.module.service_issue_payment_status.domain.dto.request.ServiceIssuePaymentStatusRequest;
import com.banesco.module.service_issue_payment_status.domain.dto.response.ServiceIssuePaymentStatusResponse;
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("/service-issue-payment-status")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ServiceIssuePaymentStatusResource {

    private final ServiceIssuePaymentStatusUseCase useCase;

    @Inject
    public ServiceIssuePaymentStatusResource(
        MessageHelper messageHelper,
        ServiceIssuePaymentStatusUseCase useCase
    ) {
        this.useCase = useCase;
    }

    @GET
    @Path("/retrieve/{paymentStatusId}/{channelCode}")
    @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 = {ServiceIssuePaymentStatusResponse.class}
                        ),
                        @SchemaProperty(
                            name = "statusResponse",
                            implementation = StatusResponse.class
                        )
                    }
                ),
                examples = @ExampleObject(
                    name = "Ejemplo exitoso",
                    value = """
                    {
                      "data": {
                        "servicingIssueProcedure": {
                          "instructionReference": {
                            "instructionIdentifier": {
                              "identification": {
                                "identifierValue": "11"
                              },
                              "identificationType": "INSTRUCTION_NUMBER"
                            }
                          },
                          "procedureType": "42",
                          "bankingProduct": {
                            "productType": "MOBILE_PAYMENT",
                            "productDescription": "PAGO MOVIL"
                          },
                          "customerReference": {
                            "partyIdentification": [
                              {
                                "partyIdentification": {
                                  "identifierValue": "V2"
                                }
                              }
                            ]
                          },
                          "associatedPartyReference": {
                            "partyIdentification": [
                              {
                                "partyIdentification": {
                                  "identifierValue": "V1"
                                }
                              }
                            ]
                          },
                          "transaction": {
                            "financialTransaction": {
                              "amount": 100,
                              "currencyCode": "VES"
                            },
                            "transactionStatus": {
                              "identification": {
                                "identifierValue": "9"
                              },
                              "statusType": "COMPLETED",
                              "statusName": "EXITOSA",
                              "statusRejectedCause": null
                            },
                            "transactionDate": [
                              {
                                "dateType": "INITIATED_DATE",
                                "date": "2025-12-22 15:49:02.7052247",
                                "time": null
                              },
                              {
                                "dateType": "EXECUTED_DATE",
                                "date": "2025-12-22 16:27:46.3739646",
                                "time": null
                              },
                              {
                                "dateType": "AVAILABLE_DATE",
                                "date": "2025-12-22 15:49:02.7052247",
                                "time": null
                              },
                              {
                                "dateType": "EXPIRY_DATE",
                                "date": "2026-12-31 00:00:00.0000000",
                                "time": null
                              },
                              {
                                "dateType": "EXPIRY_TIME",
                                "date": null,
                                "time": 0
                              }
                            ],
                            "transactionTrace": {
                              "traceChannel": "TEST",
                              "traceReference": "TEST"
                            },
                            "transactionAuthorization": {
                              "identification": {
                                "identifierValue": null
                              },
                              "authorizationType": null
                            },
                            "transactionDetails": {
                              "transactionDataJson": null
                            },
                            "description": "Pago a Fulano"
                          },
                          "workProduct": {
                            "productIdentification": {
                              "identifierValue": null
                            },
                            "productReference": "1"
                          }
                        }
                      },
                      "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 = {ServiceIssuePaymentStatusResponse.class}
                        ),
                        @SchemaProperty(
                            name = "statusResponse",
                            implementation = StatusResponse.class
                        )
                    }
                ),
                examples = {
                    @ExampleObject(
                        name = "Error VDE01 - Campo obligatorio",
                        value = """
                        {
                          "data": null,
                          "statusResponse": {
                            "statusCode": "VDE01",
                            "message": "El campo paymentStatusId 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 = {ServiceIssuePaymentStatusResponse.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 = {ServiceIssuePaymentStatusResponse.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(
        @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,

        @PathParam("paymentStatusId")
        @Parameter(description = "Identificacion del archivo", required = true, example = "11")
        String paymentStatusId,

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

        @QueryParam("deviceType")
        @Parameter(description = "Tipo de dispositivo", example = "Mobile")
        String deviceType,

        @QueryParam("deviceDescription")
        @Parameter(description = "Descripcion del dispositivo", example = "Xiaomi Note 11 PRO")
        String deviceDescription,

        @QueryParam("deviceIp")
        @Parameter(description = "Direccion IP del dispositivo", example = "127.0.0.1")
        String deviceIp,

        @QueryParam("deviceSessionReference")
        @Parameter(description = "Referencia de la peticion del dispositivo", example = "12345678901304")
        String deviceSessionReference
    ) {
        log.info("Iniciando consulta para instruccion de archivo id: {}", paymentStatusId);

        return useCase.execute(
            ServiceIssuePaymentStatusRequest.builder()
                .customerReferenceFintechId(Objects.toString(customerReferenceFintechId, ""))
                .appId(Objects.toString(appId, ""))
                .procedureRequest(Instruction.fromResource(
                    paymentStatusId, channelCode
                ))
                .device(
                    Device.builder()
                        .deviceType(deviceType)
                        .deviceDescription(deviceDescription)
                        .deviceIp(deviceIp)
                        .deviceSessionReference(deviceSessionReference)
                        .build()
                )
                .build()
        );
    }
}