import log from "../config/log";
import transactionDB from "../models/transaction.model";

export const updateHoldedTransactions = async ({
    clientId,
    paymentId,
    holdAmount,
    tenantId,
}: any
) => {
    const C = "Update Transaction Hold";
    const F = "updateHoldedTransactions";

    let totalHold = Number(holdAmount);

    log.info(`[${C}], [${F}], Tenant Id [${tenantId}], Client Id [${clientId}], Payment Id [${paymentId}]`);

    try {
        // Validate hold amount
        if (!Number.isFinite(totalHold) || totalHold <= 0) {
            log.info(`[${C}], [${F}], Tenant Id [${tenantId}], Client Id [${clientId}], Payment Id [${paymentId}], Invalid hold amount [${holdAmount}]`);
            return;
        }

        log.info(`[${C}], [${F}], Tenant Id [${tenantId}], Client Id [${clientId}], Payment Id [${paymentId}], Starting hold allocation, Total Hold [${totalHold}]`);

        const transactions = await transactionDB.getAllByGId({
            gId: paymentId
        });

        if (!Array.isArray(transactions) || transactions.length === 0) {
            log.info(`[${C}], [${F}], Tenant Id [${tenantId}], Client Id [${clientId}], Payment Id [${paymentId}], No transactions found`);
            return;
        }

        log.info(`[${C}], [${F}], Tenant Id [${tenantId}], Client Id [${clientId}], Payment Id [${paymentId}], Transactions Found [${transactions.length}]`);

        for (const transaction of transactions) {

            if (totalHold <= 0) {
                log.info(`[${C}], [${F}], Tenant Id [${tenantId}], Client Id [${clientId}], Payment Id [${paymentId}], Hold allocation completed, Remaining Hold [${totalHold}]`);
                break;
            }

            const transactionId = transaction?.id;
            const amount = Number(transaction?.amount);

            // Validate transaction amount
            if (!Number.isFinite(amount) || amount <= 0) {
                log.info(`[${C}], [${F}], Tenant Id [${tenantId}], Client Id [${clientId}], Payment Id [${paymentId}], Skipping transaction [${transactionId}], Invalid Amount [${transaction?.amount}]`);
                continue;
            }

            // Calculate hold amount for current transaction
            const allocatedHold = Math.min(amount, totalHold);

            log.info(
                `[${C}], [${F}], Tenant Id [${tenantId}], Client Id [${clientId}], Payment Id [${paymentId}], Processing Transaction [${transactionId}], Amount [${amount}], Allocating Hold [${allocatedHold}], Remaining Before [${totalHold}]`
            );

            await transactionDB.updateHoldAmount({
                id: transactionId,
                holdAmount: allocatedHold
            });

            totalHold = totalHold - allocatedHold;

            log.info(
                `[${C}], [${F}], Tenant Id [${tenantId}], Client Id [${clientId}], Payment Id [${paymentId}], Transaction [${transactionId}] updated successfully, Allocated Hold [${allocatedHold}], Remaining Hold [${totalHold}]`
            );
        }

        if (totalHold > 0) {
            log.info(
                `[${C}], [${F}], Tenant Id [${tenantId}], Client Id [${clientId}], Payment Id [${paymentId}], Hold allocation incomplete, Unallocated Amount [${totalHold}]`
            );
        } else {
            log.info(`[${C}], [${F}], Tenant Id [${tenantId}], Client Id [${clientId}], Payment Id [${paymentId}], Hold allocation completed successfully`);
        }
        return;

    } catch (error: any) {
        log.info(
            `[${C}], [${F}], Tenant Id [${tenantId}], Client Id [${clientId}], Payment Id [${paymentId}], Error updating transaction holds, Remaining Hold [${totalHold}], Error [${error?.message}], Stack [${error?.stack}]`
        );

        return;
    }
};
