// dollarbazar.payout.service.js

const axios = require("axios");
const crypto = require("crypto");

const DBZ_BASE = "https://api.dollarbazar.co/finance-service";

// const API_KEY = process.env.DBZ_API_KEY;
// const CLIENT_ID = process.env.DBZ_CLIENT_ID;
// const SALT = process.env.DBZ_SALT;

// PayOut (DIFFERENT CREDENTIALS)
const DBZ_PAYOUT_API_KEY = process.env.DBZ_PAYOUT_API_KEY;
const DBZ_PAYOUT_CLIENT_ID = process.env.DBZ_PAYOUT_CLIENT_ID;
const DBZ_PAYOUT_SALT = process.env.DBZ_PAYOUT_SALT;

const USERNAME = process.env.DBZ_USERNAME;

//----------------------------------------
// 1. AUTHENTICATION
//----------------------------------------
async function getAuthTokens(amount, orderId) {
    const str =
        `apiKey=${DBZ_PAYOUT_API_KEY}~clientId=${DBZ_PAYOUT_CLIENT_ID}~amount=${amount}~orderId=${orderId}${DBZ_PAYOUT_SALT}`
    console.log("🚀 ~ getAuthTokens ~ str:", str)

    const hash = crypto.createHash("sha256").update(str).digest("hex").toUpperCase();
    console.log("🚀 ~ getAuthTokens ~ hash:", hash)

    const body = {
        amount,
        apiKey: DBZ_PAYOUT_API_KEY,
        clientId: DBZ_PAYOUT_CLIENT_ID,
        orderId,
        hash,
    };
    console.log("🚀 ~ getAuthTokens ~ auth hash log :", `${DBZ_BASE}/api/authenticateByHash`)

    const res = await axios.post(`${DBZ_BASE}/api/authenticateByHash`, body);
    console.log("🚀 ~ getAuthTokens ~ res--data:", res.data)
    if (!res?.data || !res?.data || !res?.data?.api_token) {
        throw new Error("DollarBazar Authentication failed");
    }

    return {
        api_token: res?.data.api_token,
        // api_token: 'BSX4MzMZKnb4g0JFYGEzk-pvPx4a7ZtQfduKmkfHhTsJJNsfLaNHlPufPSfA',
        id_token: res?.data.id_token,
    };
}

//----------------------------------------
// 2. DO PAYOUT
//----------------------------------------
async function doPayout(amount, bank, orderId) {
    console.log("🚀 ~ amount ~ amount:", amount)
    console.log("🚀 ~ orderId ~ orderId:", orderId)

    const auth = await getAuthTokens(amount, orderId);

    const payoutBody = {
        amount: String(amount),
        orderId: String(orderId),
        api_token: auth.api_token,
        id_token: auth.id_token,
        userName: USERNAME,               // required
        client_id: DBZ_PAYOUT_CLIENT_ID,  // required
        hash: "NA",                       // according to docs or your PG provider
        accountNumber: bank.ac_number,
        ifscCode: bank.ifsc_code,
        bankName: bank.bank_name,
        beneficiaryName: bank.ac_holder_name,
        mobileNumber: bank.mobile_number || "9482345952",
        remittanceAmount: String(amount),
        type: "IMPS",
        route: "IMPS"
    };
    console.log("🚀 ~ doPayout ~ payoutBody:", payoutBody)
    console.log("~~~~~~~~~~~test 11111~~~~~~~~~~~~~~~ ",)

    // const res = await axios.post(
    //     `${DBZ_BASE}/api/user/combined-init-complete-payout`,
    //     payoutBody,
    //     {
    //         headers: {
    //             apiauthorization: `Bearer ${auth?.api_token}`,
    //             Authorization: `Bearer ${auth?.id_token}`,
    //         }
    //     }
    // );

    const res = await axios.post(
        `${DBZ_BASE}/api/user/combined-init-complete-payout`,
        payoutBody,
        {
            headers: {
                "Content-Type": "application/json",
                "api-Authorization": `Bearer ${auth.api_token}`,   // FIXED !!!
                "Authorization": `Bearer ${auth.id_token}`
            }
        }
    );



    console.log("~~~~~~~~~~~test 22222~~~~~~~~~~~~~~~ ",)
    console.log("🚀 ~~~~~~~~~~~~~~~~~~~~~~~~~~ doPayout ~ res:", res)

    const data = res.data;

    if (!data.success) {
        return {
            status: "FAILED",
            message: data.msg || "Payout failed"
        };
    }

    return {
        status: "SUCCESS",
        utr: data?.data?.bankRefId || "",
        tnxId: data?.data?.tnxId || "",
        message: data.msg || "Payout successful"
    };
}


//----------------------------------------
// 3. CHECK STATUS
//---------------------------------------
async function checkPayoutStatus(api_token, id_token, orderId) {
    const res = await axios.get(
        `${DBZ_BASE}/api/user/get-payment-details/${orderId}`,
        {
            headers: {
                apiauthorization: `Bearer ${api_token}`,
                Authorization: `Bearer ${id_token}`,
            }
        }
    );

    return res.data;
}





module.exports = {
    doPayout,
    getAuthTokens,
    checkPayoutStatus
};
