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

import com.banesco.common.application.helper.ErrorResponseHelper;
import com.banesco.common.domain.exception.BaseApiException;
import com.banesco.common.domain.model.ApiResponse;
import com.banesco.module.legal_customer_product_directory.application.usecase.LegalCustomerProductDirectoryUseCase;
import com.banesco.module.legal_customer_product_directory.domain.dto.request.LegalCustomerProductDirectoryRequest;
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.parameters.Parameter;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;

import java.util.Objects;

@Slf4j
@Path("/rec-legal-customer-product-directory")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class LegalCustomerProductDirectoryResource {
    private final LegalCustomerProductDirectoryUseCase useCase;
    private final ErrorResponseHelper errorResponseHelper;

    @Inject
    public LegalCustomerProductDirectoryResource(
        LegalCustomerProductDirectoryUseCase useCase,
        ErrorResponseHelper errorResponseHelper
    ) {
        this.useCase = useCase;
        this.errorResponseHelper = errorResponseHelper;
    }

    @GET
    @Path("/retrieve/{customerIbsNumber : (?!retrieve$).*}")
    @Operation(
        summary = "Recuperar productos de cliente legal",
        description = "Consulta masiva de cuentas por número de cliente IBS"
    )
    @APIResponses(value = {
        @APIResponse(
            responseCode = "200",
            description = "Operación exitosa",
            content = @Content(
                mediaType = MediaType.APPLICATION_JSON,
                schema = @Schema(implementation = ApiResponse.class),
                examples = @ExampleObject(
                    name = "Ejemplo exitoso",
                    value = """
                    {
                      "data": {
                        "customerProductAndServiceDirectory": {
                          "party": {
                            "partyName": [
                              {
                                "fullName": "TASCA RESTAURANT GOOD WORLD CEN, C.A."
                              }
                            ],
                            "partyType": "ORGANISATION",
                            "partyDateTime": [],
                            "partyIdentification": [
                              {
                                "partyIdentificationType": "TAX_IDENTIFICATION_NUMBER",
                                "partyIdentification": {
                                  "identifierValue": "J000000001",
                                  "issuingAuthority": ""
                                }
                              }
                            ],
                            "partyLegalStructureType": ""
                          },
                          "accounts": [
                            {
                              "accountStatus": {
                                "status": "D"
                              },
                              "accountIdentification": [
                                {
                                  "accountIdentificationType": "NUMERO_CUENTA",
                                  "accountIdentification": {
                                    "identifierValue": "01340025330253093528",
                                    "issuingAuthority": ""
                                  }
                                },
                                {
                                  "accountIdentificationType": "NUMERO_BANCO",
                                  "accountIdentification": {
                                    "identifierValue": "01",
                                    "issuingAuthority": ""
                                  }
                                },
                                {
                                  "accountIdentificationType": "CODIGO_PRODUCTO",
                                  "accountIdentification": {
                                    "identifierValue": "3980",
                                    "issuingAuthority": ""
                                  }
                                },
                                {
                                  "accountIdentificationType": "CLASE_CUENTA",
                                  "accountIdentification": {
                                    "identifierValue": "80",
                                    "issuingAuthority": ""
                                  }
                                },
                                {
                                  "accountIdentificationType": "TIPO_CUENTA",
                                  "accountIdentification": {
                                    "identifierValue": "MMK",
                                    "issuingAuthority": ""
                                  }
                                }
                              ],
                              "accountBalance": [
                                {
                                  "balanceAmount": 390417.36,
                                  "balanceType": "SALDO_DISPONIBLE"
                                },
                                {
                                  "balanceAmount": 100000.00,
                                  "balanceType": "MAXIMO_DIARIO"
                                },
                                {
                                  "balanceAmount": 100000.00,
                                  "balanceType": "MAXIMO_TRANSACCION"
                                },
                                {
                                  "balanceAmount": 3000000.00,
                                  "balanceType": "MAXIMO_MENSUAL"
                                },
                                {
                                  "balanceAmount": 0.01,
                                  "balanceType": "MINIMO_TRANSACCION"
                                }
                              ],
                              "accountCurrency": [
                                {
                                  "currencyCode": "BS",
                                  "currencyType": "BASE"
                                }
                              ],
                              "accountDescription": "TASCA RESTAURANT GOOD WORLD CEN, C.A.",
                              "accountInvolvement": [
                                {
                                  "accountInvolvementType": "CONTACTO_TELEFONICO",
                                  "partyReference": {
                                    "partyIdentification": [
                                      {
                                        "partyIdentificationType": "TELEPHONE_NUMBER",
                                        "partyIdentification": {
                                          "identifierValue": "04122710660",
                                          "issuingAuthority": ""
                                        }
                                      }
                                    ]
                                  }
                                }
                              ]
                            }
                          ]
                        }
                      },
                      "statusResponse": {
                        "statusCode": "200",
                        "message": "Operación exitosa"
                      }
                    }
                    """
                )
            )
        ),
        @APIResponse(
            responseCode = "400",
            description = "Error en formato o campo requerido",
            content = @Content(
                mediaType = MediaType.APPLICATION_JSON,
                schema = @Schema(implementation = ApiResponse.class),
                examples = {
                    @ExampleObject(
                        name = "Error VDE01 - Campo obligatorio",
                        value = """
                        {
                          "data": null,
                          "statusResponse": {
                            "statusCode": "VDE01",
                            "message": "El campo customerIbsNumber 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 accountStatus. Valores permitidos: A, O, ACTBSUSD"
                          }
                        }
                        """
                    )
                }
            )
        ),
        @APIResponse(
            responseCode = "401",
            description = "No autorizado",
            content = @Content(
                mediaType = MediaType.APPLICATION_JSON,
                schema = @Schema(implementation = ApiResponse.class),
                examples = {
                    @ExampleObject(
                        name = "Error VRN08 - Identificación 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),
                examples = {
                    @ExampleObject(
                        name = "Error VRN04 - Fuera de horario",
                        value = """
                        {
                          "data": null,
                          "statusResponse": {
                            "statusCode": "VRN04",
                            "message": "El servicio no está disponible fuera del horario operativo"
                          }
                        }
                        """
                    ),
                    @ExampleObject(
                        name = "Error VDR13 - OSB no disponible",
                        value = """
                        {
                          "data": null,
                          "statusResponse": {
                            "statusCode": "VDR13",
                            "message": "El servicio OSB no está disponible en este momento"
                          }
                        }
                        """
                    )
                }
            )
        )
    })
    public Response retrieve(
        @HeaderParam("customerReferenceFintechId")
        @Parameter(description = "ID de la fintech", required = true, example = "pranical-test")
        String customerReferenceFintechId,

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

        @PathParam("customerIbsNumber")
        @Parameter(description = "Número de cliente IBS (VCUSCUN)", example = "200053197")
        String customerIbsNumber,

        @QueryParam("bankNumber")
        @Parameter(description = "Número de banco (VACMBNK)", example = "01")
        String bankNumber,

        @QueryParam("currencyCode")
        @Parameter(description = "Código de moneda (VACMCCY)", example = "BS")
        String currencyCode,

        @QueryParam("accountStatus")
        @Parameter(description = "Estatus de cuenta (VACMAST). 'A'=Activa BS, 'O'=Activa USD, 'ACTBSUSD'=Ambas", example = "A")
        String accountStatus,

        @QueryParam("productCvCode")
        @Parameter(description = "Código de Producto Cuenta Verde (VACMPROCV). 'CV'=Cuenta verde, 'CVFL'=Cuenta verde con opción activa", example = "CV")
        String productCvCode,

        @QueryParam("productCode")
        @Parameter(description = "Código de producto (VACMPRO)", example = "3980")
        String productCode,

        @QueryParam("channelCode")
        @Parameter(description = "Código de canal (VAFILICANAL)", example = "APP")
        String channelCode,

        @QueryParam("serviceType")
        @Parameter(description = "Tipo de servicio (VAFILICOSER)", example = "P2P")
        String serviceType,

        @QueryParam("affiliationStatus")
        @Parameter(description = "Estatus de afiliación (VAFILISTATU)", example = "A")
        String affiliationStatus,

        @QueryParam("limitType")
        @Parameter(description = "Pagador/Receptor (VALIMIT). 'PAG'=Pagadora, 'REC'=Receptora", example = "PAG")
        String limitType,

        @QueryParam("casheaIndicator")
        @Parameter(description = "Indicador cash (VCASHEA). 'SI'=En tabla cashea, 'NO'=No en tabla cashea", example = "SI")
        String casheaIndicator
    ) {
        log.info("Iniciando consulta para cliente IBS: {}", customerIbsNumber);

        try {
            return Response.ok(useCase.execute(
                LegalCustomerProductDirectoryRequest.builder()
                    .customerIbsNumber(Objects.toString(customerIbsNumber, ""))
                    .customerReferenceFintechId(customerReferenceFintechId)
                    .appId(appId)
                    .bankNumber(Objects.toString(bankNumber, ""))
                    .currencyCode(Objects.toString(currencyCode, ""))
                    .accountStatus(Objects.toString(accountStatus, ""))
                    .productCvCode(Objects.toString(productCvCode, ""))
                    .productCode(Objects.toString(productCode, ""))
                    .channelCode(Objects.toString(channelCode, ""))
                    .serviceType(Objects.toString(serviceType, ""))
                    .affiliationStatus(Objects.toString(affiliationStatus, ""))
                    .limitType(Objects.toString(limitType, ""))
                    .casheaIndicator(Objects.toString(casheaIndicator, ""))
                    .build()
            )).build();
        } catch (BaseApiException e) {
            return errorResponseHelper.handleException(e);
        } catch (Exception e) {
            return errorResponseHelper.handleGenericException(e);
        }
    }
}