const dbConnect = require('../../busapi/configs/dbConnection.js');
const ep = require("../../busapi/controllers/enquirePaymentController.js")

const buildMakePaymentBody = async (reqBody) => {
    console.log("request received");
  try {
    // --- 1️⃣ Basic required fields ---
    const requiredFields = ["customerid", "validationid", "source_ref_no"];
    for (const field of requiredFields) {
      if (!reqBody[field]) {
        return {
          flow: "error",
          error: {
            code: 4001, 
            message: `Missing required field: ${field}`,
          },
        };
      }
    }
    
    

    // --- 2️⃣ Object name validation ---
    const allowedObjects = [
      "customerid",
      "validationid",
      "source_ref_no",
      "orderid",
      "payment_amount",
      "customer",
      "device",
    ];

    for (const key of Object.keys(reqBody)) {
      if (!allowedObjects.includes(key)) {
        return {
          flow: "error",
          error: {
            code: 4002,
            message: `Invalid object name in body: '${key}'. Please verify your request keys.`,
          },
        };
      }
    }
   
    // --- 3️⃣ Get payment_account details ---
    
    // const authenticators = reqBody.authenticatorsFromUI;
    // if (!Array.isArray(authenticators) || authenticators.length === 0) {
    //   return {
    //     flow: "error",
    //     error: {
    //       code: 4003,
    //       message: "At least one authenticator is required",
    //     },
    //   };
    // }

    // for (const auth of authenticators) {
    //   if (!auth.parameter_name || !auth.value) {
    //     return {
    //       flow: "error",
    //       error: {
    //         code: 4004,
    //         message: "Authenticator parameter_name and value are required",
    //       },
    //     };
    //   }
    // }
    const orderid = reqBody.orderid;
    const pa = await ep.enquirePayment(orderid, transactionid=""); //it is required field in enquire payment api, although only 1 is essential for bd api
    
    return pa;
    const payment_method = {};
    // if(payment_method" == "BankAccount") {
    //     "payment_account"= { 
    //         "payment_method": "BankAccount", 
    //         "remitter_name":"Aditya Kumar", 
    //         "account_number": "12547300001", 
    //         "ifsc": "HDFC0000114"
    //     }
    // }
    // else if("payment_method" == "DebitCard") {
    //     "payment_account"= { 
    //         "payment_method": "DebitCard", 
    //         "remitter_name": "Aditya Kumar", 
    //         "card_start": "454198", 
    //         "card_end": "4825", 
    //         "card_issuer": "ABC Bank"
    //     }
    // } 
    // else if("payment_method" == "CreditCard") {
    //     "payment_account"= { 
    //         "payment_method": "CreditCard", 
    //         "remitter_name": "Aditya Kumar", 
    //         "card_start": "454198", 
    //         "card_end": "4825", 
    //         "card_issuer": "ABC Bank"
    //     }
    // }
    // else if("payment_method" == "CreditCard") {
    //     "payment_account"= { 
    //         "payment_method": "CreditCard", 
    //         "remitter_name": "Aditya Kumar", 
    //         "card_start": "454198", 
    //         "card_end": "4825", 
    //         "card_issuer": "ABC Bank"
    //     }
    // }
    // else if("payment_method" == "UPI") {
    //     "payment_account"= { 
    //         "payment_method": "UPI", 
    //         "remitter_name": "Aditya Kumar", 
    //         "vpa": "8237476948@okaxis"
    //     }
    // }
     

    ///////////////////////////////////////////////////////////////////////////////////////

    // --- 4️⃣ Validate customer section ---
    const customer = reqBody.customer || {};
    if (!customer.firstname || !customer.mobile) {
      return {
        flow: "error",
        error: {
          code: 4005,
          message: "Incomplete customer details provided",
        },
      };
    }

    // --- 5️⃣ Validate device info based on init_channel ---
    const device = reqBody.device || {};
    if (!device.init_channel) {
      return {
        flow: "error",
        error: {
          code: 4006,
          message: "Device init_channel is required",
        },
      };
    }

    if (device.init_channel === "Internet") {
      if (!device.ip || !device.mac) {
        return {
          flow: "error",
          error: {
            code: 4007,
            message: "Internet device must include ip and mac",
          },
        };
      }
    } else if (device.init_channel === "Mobile") {
      if (!device.imei || !device.os || !device.app) {
        return {
          flow: "error",
          error: {
            code: 4008,
            message: "Mobile device must include imei, os, and app",
          },
        };
      }
    }
    
    let agentId;
    // Choose agent ID dynamically based on init_channel
    if (device.init_channel === "Internet") {
        agentId = process.env.BBPS_INTERNET_AGENT_ID;
    } else {
        agentId = process.env.BBPS_MOBILE_AGENT_ID;
    } 

    // --- 6️⃣ Build the final payload ---
    const finalBody = {
      customerid: reqBody.customerid,
      validationid: reqBody.validationid,
      source_ref_no: reqBody.source_ref_no,
      
      debit_amount: reqBody.debit_amount,
      currency: "356",
      payment_type: "instapay",
    
    
      customer,
      metadata: {
        agent: {
          agentid: agentId,
        },
        device,
      },
      risk: [
        {
          score_provider: "BD01",
          score_value: "030",
          score_type: "TXNRISK",
        },
        {
          score_provider: "BBPS",
          score_value: "030",
          score_type: "TXNRISK",
        },
      ],
    };

    if (reqBody.cou_conv_fee) {
      finalBody.cou_conv_fee = reqBody.cou_conv_fee;
    }
    if (reqBody.bou_conv_fee) {
      finalBody.bou_conv_fee = reqBody.bou_conv_fee;
    }
    if (reqBody.payment_amount) {
      finalBody.payment_amount = reqBody.payment_amount;
    }
    

    return { flow: "makePayment", body: finalBody };
  } catch (err) {
    return {
      flow: "error",
      error: {
        code: 5000,
        message: `Unexpected error while building body: ${err.message}`,
      },
    };
  }
};

module.exports = { buildMakePaymentBody };


