package com.banesco.module.payment_initiation_request.infrastructure.mapper;

import com.banesco.common.domain.model.Identifier;
import com.banesco.module.payment_request.domain.dto.request.PaymentRequestRequest;
import com.banesco.module.payment_request.domain.model.Operation;
import com.banesco.module.payment_request.domain.model.PaymentRequest;
import com.banesco.module.payment_initiation_request.domain.dto.request.PaymentInitiationRequestRequest;
import com.banesco.module.payment_initiation_request.domain.model.PaymentInitiationTransaction;
import com.banesco.module.transaction.domain.model.*;
import io.netty.util.internal.StringUtil;

import java.util.List;

public class ServicingIssueMapper {

    private ServicingIssueMapper() {}

    public static PaymentRequestRequest toPaymentRequest(
        PaymentInitiationRequestRequest request
    ) {
        return PaymentRequestRequest.builder()
            .fintechId(request.getCustomerReferenceFintechId())
            .operation(
                Operation.builder()
                    .operationTypeCode(mapPaymentTransactionType(
                        request.getPaymentTransactionType()
                    ))
                    .recipientId(request.getPayeeId())
                    .applicantId(request.getPayerId())
                    .amount(request.getAmount())
                    .currency(request.getCurrency())
                    .concept(request.getPurpose())
                    .build()
            )
            .channelOrigin(request.getProcedureRequest().getInstructionPurposeType().name())
            .build();
    }

    public static PaymentInitiationTransaction toModel(PaymentRequest response) {
        return PaymentInitiationTransaction.builder()
            .transaction(buildTransaction(response))
            .build();
    }

    private static Transaction buildTransaction(PaymentRequest response) {
        return Transaction.builder()
            .transactionIdentification(
                Identifier.builder()
                    .identifierValue(String.valueOf(response.getId()))
                    .build()
            )
            .transactionDate(buildTransactionDateTimeList(response))
            .build();
    }

    private static List<TransactionDateTime> buildTransactionDateTimeList(PaymentRequest response) {
        return List.of(
            TransactionDateTime.builder()
                .dateType(TransactionDateTimeType.INITIATED_DATE)
                .date(response.getDateCreate())
                .build()
        );
    }

    private static String mapPaymentTransactionType(String paymentTransactionType) {
        if (StringUtil.isNullOrEmpty(paymentTransactionType)) {
            return null;
        }

        return switch (paymentTransactionType.toUpperCase()) {
            case "MOBILE_PAYMENT" -> "PAGO_MOVIL";
            default -> "";
        };
    }
}