const { getBBPSConfig } = require("../utils/config");
const { callBBPS } = require("../utils/bbpsClient");
const dbConnect = require('../../busapi/configs/dbConnection');

exports.getRechargePlans = async (req, res) => {
  try {
    const { billerid, mobile } = req.body;

    if (!billerid) {
      return res.status(400).json({
        success: false,
        message: "billerid is required",
      });
    }
    
    // Validate mobile (only if provided)
    if (mobile && (!/^\d{10}$/.test(mobile))) {
      return res.status(400).json({
        success: false,
        message: "Invalid mobile number. Must be 10 digits."
      });
    }

    //console.log("📥 Incoming Request:", { billerid, mobile });

    // 1️⃣ Fetch biller info from DB
    const [biller] = await dbConnect.query(
      "SELECT billerid, biller_category, plan_available FROM biller_all WHERE billerid = ?",
      [billerid]
    );

    if (!biller || biller.length === 0) {
      return res.status(404).json({
        success: false,
        message: "Biller not found",
      });
    }
    

    const billerData = biller[0];
    const planFlag = (billerData.plan_available || '').toUpperCase();
    const category = (billerData.biller_category || '').toUpperCase();
    
 
    if (planFlag !== 'Y') {
      console.log(`ℹ️ Biller ${billerid} does not support plans`);
      return res.status(200).json({
        success: true,
        data: [],
        message: "Recharge plans not available for this biller"
      });
    }

    //console.log("ℹ️ Biller Info:", billerData);

    // 2️⃣ Decide API type
    let apiType = "STATIC";
    if (planFlag === "Y" && category === "MOBILE PREPAID") {
      if (["AIRTELPRE", "JIOPRE"].includes(billerid.toUpperCase())) {
        if (mobile) {
          apiType = "121";
        } else {
          console.warn("⚠️ Mobile not provided for 121 API, falling back to static");
        }
      }
    }
    if (planFlag === "Y" && category === "DTH") {
      apiType = "STATIC"; // since no 121 API available for DTH
    }

    //console.log(`🚀 Selected API Type: ${apiType}`);

    // 3️⃣ Build request payload
    const payload =
      apiType === "121"
        ? { plan_type: "121", billerid, mobile }
        : { billerid };

    //console.log("📦 Payload:", payload);

    // 4️⃣ Prepare config
    const config = getBBPSConfig();

    // 5️⃣ Call BBPS internal API via unified utility
    let response;
    try {
      response = await callBBPS({
        path: "billpay/plans/retrieve",
        payload,
        config,
        lineEndings: "crlf",
      });
      //console.log("✅ BBPS Response Received:", response);
    } catch (err) {
      console.error("❌ 121 API failed:", err.message);
      if (apiType === "121") {
        // fallback to static
        const staticPayload = { billerid };
        response = await callBBPS({
          path: "billpay/plans/retrieve",
          payload: staticPayload,
          config,
          lineEndings: "crlf",
        });
        apiType = "STATIC (fallback)";
        //console.log("🔁 Retried Static after 121 failure");
      } else {
        throw err;
      }
    }

    // 6️⃣ Send decrypted response back
    return res.status(200).json({
      success: true,
      source: apiType,
      data: response,
    });
  } catch (error) {
    console.error("💥 Error in getRechargePlans:", error);
    return res.status(500).json({
      success: false,
      message: "Failed to fetch recharge plans",
      error: error.message,
    });
  }
};
