package com.banesco.module.legal_customer_product_directory.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.legal_customer_product_directory.application.usecase.LegalCustomerProductDirectoryUseCase;
import com.banesco.module.legal_customer_product_directory.domain.dto.request.LegalCustomerProductDirectoryRequest;
import com.banesco.module.legal_customer_product_directory.domain.dto.response.LegalCustomerProductDirectoryResponse;
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("/customer/accounts")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class LegalCustomerProductDirectoryResource {

    private final LegalCustomerProductDirectoryUseCase useCase;
    private final MessageHelper messageHelper;

    @Inject
    public LegalCustomerProductDirectoryResource(
        LegalCustomerProductDirectoryUseCase useCase,
        MessageHelper messageHelper
    ) {
        this.useCase = useCase;
        this.messageHelper = messageHelper;
    }

    @GET
    @Path("/retrieve/{customerId : (?!retrieve$).*}")
    @Operation(
        summary = "Recuperar productos de cliente legal",
        description = "Consulta masiva de cuentas por numero de cliente IBS"
    )
    @APIResponses(value = {
        @APIResponse(
            responseCode = "200",
            description = "Operacion exitosa",
            content = @Content(
                mediaType = MediaType.APPLICATION_JSON,
                schema = @Schema(
                    implementation = ApiResponse.class,
                    properties = {
                        @SchemaProperty(
                            name = "data",
                            oneOf = {LegalCustomerProductDirectoryResponse.class}
                        ),
                        @SchemaProperty(
                            name = "statusResponse",
                            implementation = StatusResponse.class
                        )
                    }
                ),
                examples = @ExampleObject(
                    name = "Ejemplo exitoso",
                    value = """
                    {
                      "data": {
                        "customerProductAndServiceDirectory": {
                          "accounts": [
                            {
                              "accountStatus": {
                                "status": "A",
                                "statusType": "ENABLED"
                              },
                              "accountType": "CURRENT_ACCOUNT",
                              "accountIdentification": [
                                {
                                  "accountIdentificationType": "ACCOUNT_NUMBER",
                                  "accountIdentification": {
                                    "identifierValue": "01340025330253093528"
                                  }
                                },
                                {
                                  "accountIdentificationType": "BANK_NUMBER",
                                  "accountIdentification": {
                                    "identifierValue": "01"
                                  }
                                },
                                {
                                  "accountIdentificationType": "PRODUCT_CODE",
                                  "accountIdentification": {
                                    "identifierValue": "3980"
                                  }
                                },
                                {
                                  "accountIdentificationType": "ACCOUNT_CLASS",
                                  "accountIdentification": {
                                    "identifierValue": "80"
                                  }
                                }
                              ],
                              "accountBalance": [
                                {
                                  "balanceAmount": 390417.36,
                                  "balanceType": "AVAILABLE_BALANCE"
                                },
                                {
                                  "balanceAmount": 100000.00,
                                  "balanceType": "DAILY_MAXIMUM"
                                },
                                {
                                  "balanceAmount": 3000000.00,
                                  "balanceType": "MONTHLY_MAXIMUM"
                                },
                                {
                                  "balanceAmount": 0.01,
                                  "balanceType": "TRANSACTION_MINIMUM"
                                },
                                {
                                  "balanceAmount": 100000.00,
                                  "balanceType": "TRANSACTION_MAXIMUM"
                                }
                              ],
                              "accountCurrency": [
                                {
                                  "currencyCode": "BS",
                                  "currencyType": "BASE"
                                }
                              ],
                              "accountInvolvement": [
                                {
                                  "accountInvolvementType": "PARTY_IS_OWNER_OF_ACCOUNT",
                                  "partyReference": {
                                    "partyName": [
                                      {
                                        "fullName": "TASCA RESTAURANT GOOD WORLD CEN, C.A."
                                      }
                                    ],
                                    "partyType": "ORGANIZATION",
                                    "partyIdentification": [
                                      {
                                        "partyIdentificationType": "TAX_IDENTIFICATION_NUMBER",
                                        "partyIdentification": {
                                          "identifierValue": "J000000001"
                                        }
                                      },
                                      {
                                        "partyIdentificationType": "TELEPHONE_NUMBER",
                                        "partyIdentification": {
                                          "identifierValue": "04122710660"
                                        }
                                      },
                                      {
                                        "partyIdentificationType": "TELEPHONE_OPERATOR",
                                        "partyIdentification": {
                                          "identifierValue": "0412"
                                        }
                                      }
                                    ]
                                  }
                                }
                              ],
                              "accountRelationship": [
                                {
                                  "accountRelationshipType": "ACCOUNT_IS_SUB_ACCOUNT_FOR_ACCOUNT"
                                }
                              ],
                              "agreement": [
                                {
                                  "arrangement": [
                                    {
                                      "arrangementType": "INTEREST_ARRANGEMENT"
                                    }
                                  ]
                                }
                              ]
                            }
                          ]
                        }
                      },
                      "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 = {LegalCustomerProductDirectoryResponse.class}
                        ),
                        @SchemaProperty(
                            name = "statusResponse",
                            implementation = StatusResponse.class
                        )
                    }
                ),
                examples = {
                    @ExampleObject(
                        name = "Error VDE01 - Campo obligatorio",
                        value = """
                        {
                          "data": null,
                          "statusResponse": {
                            "statusCode": "VDE01",
                            "message": "El campo customerId 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,
                    properties = {
                        @SchemaProperty(
                            name = "data",
                            oneOf = {LegalCustomerProductDirectoryResponse.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 = {LegalCustomerProductDirectoryResponse.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 = "pranical-test")
        String customerReferenceFintechId,

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

        @PathParam("customerId")
        @Parameter(description = "Numero de cliente IBS (VCUSCUN)", example = "200053197")
        String customerId
    ) {
        log.info("Iniciando consulta para cliente IBS: {}", customerId);

        try {
            return Response.ok(useCase.execute(
                LegalCustomerProductDirectoryRequest.builder()
                    .customerId(Objects.toString(customerId, ""))
                    .customerReferenceFintechId(customerReferenceFintechId)
                    .appId(appId)
                    .build()
            )).build();
        } catch (HttpStatusCodeException e) {
            return messageHelper.handleException(e);
        } catch (Exception e) {
            return messageHelper.handleGenericException(e);
        }
    }
}