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

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.correspondence.application.usecase.CorrespondenceUseCase;
import com.banesco.module.correspondence.domain.dto.request.CorrespondenceRequest;
import com.banesco.module.correspondence.domain.dto.response.CorrespondenceResponse;
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("/correspondence")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class CorrespondenceResource {

    private final CorrespondenceUseCase useCase;

    @Inject
    public CorrespondenceResource(
            CorrespondenceUseCase useCase
    ) {
        this.useCase = useCase;
    }

    @GET
    @Path("/retrieve/{securityNotificationId}/{channelCode}")
    @Operation(
        summary = "Recuperar informacion de la transaccion",
        description = "Consulta de una trasanccion de pago por id de la notificacion"
    )
    @APIResponses(value = {
        @APIResponse(
            responseCode = "200",
            description = "Operacion exitosa",
            content = @Content(
                mediaType = MediaType.APPLICATION_JSON,
                schema = @Schema(
                    implementation = ApiResponse.class,
                    properties = {
                        @SchemaProperty(
                            name = "data",
                            oneOf = {CorrespondenceResponse.class}
                        ),
                        @SchemaProperty(
                            name = "statusResponse",
                            implementation = StatusResponse.class
                        )
                    }
                ),
                examples = @ExampleObject(
                    name = "Ejemplo exitoso",
                    value = """
                    {
                      "data": {
                        "correspondence": [
                            {
                                "instructionReference": {
                                    "instructionIdentifier": {
                                        "identification": {
                                            "identifierValue": "10053"
                                        },
                                        "identificationType": "INSTRUCTION_NUMBER"
                                    }
                                },
                                "sourceReference": "1",
                                "bankingProduct": {
                                    "productType": "TRANSATIP",
                                    "productDescription": "TRANSFERENCIA MONTO ATIPICO"
                                },
                                "customerReference": {
                                    "partyIdentification": [
                                        {
                                            "partyIdentification": {
                                                "identifierValue": "v20132859"
                                            }
                                        }
                                    ]
                                },
                                "transaction": {
                                    "financialTransaction": {
                                        "amount": 1000.0,
                                        "currencyCode": "VES"
                                    },
                                    "transactionStatus": {
                                        "identification": {
                                            "identifierValue": "59"
                                        },
                                        "statusType": "EXPIRED",
                                        "statusName": "EXPIRADA",
                                        "statusDescription": "1",
                                        "statusRejectedCause": null
                                    },
                                    "transactionDate": [
                                        {
                                            "dateType": "INITIATED_DATE",
                                            "date": null,
                                            "time": null
                                        },
                                        {
                                            "dateType": "EXECUTED_DATE",
                                            "date": "2026-01-23 16:28:01.2219947",
                                            "time": null
                                        },
                                        {
                                            "dateType": "EXPIRY_DATE",
                                            "date": "2025-12-31 00:00:00.0000000",
                                            "time": null
                                        },
                                        {
                                            "dateType": "EXPIRY_TIME",
                                            "date": null,
                                            "time": 0
                                        }
                                    ],
                                    "transactionAuthorization": {
                                        "identification": {
                                            "identifierValue": null
                                        },
                                        "authorizationType": null
                                    },
                                    "transactionDetails": {
                                        "transactionDataJson": "{\\"amount\\":\\"1000.00\\",\\"currency\\":\\"VES\\"}",
                                        "transactionPage": null,
                                        "transactionPageSize": null
                                    }
                                }
                            }
                        ]
                      },
                      "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 = {CorrespondenceResponse.class}
                        ),
                        @SchemaProperty(
                            name = "statusResponse",
                            implementation = StatusResponse.class
                        )
                    }
                ),
                examples = {
                    @ExampleObject(
                        name = "Error VDE01 - Campo obligatorio",
                        value = """
                        {
                          "data": null,
                          "statusResponse": {
                            "statusCode": "VDE01",
                            "message": "El campo securityNotificationId 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 = {CorrespondenceResponse.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 = {CorrespondenceResponse.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("securityNotificationId")
        @Parameter(description = "Identificacion de la notifiacion", required = true, example = "11")
        String securityNotificationId,

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

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

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

        @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 la notificacion id: {}", securityNotificationId);

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