// billdeskpg/services/billdeskService.js
const { v4: uuidv4 } = require("uuid");
const model = require("../models/billdesk.model");
const billdeskClient = require("../utils/billdeskClient");
require("dotenv").config();

async function createOrder(body) {
  if (!body || !body.amount || !body.customer || !body.customer.first_name || !body.customer.last_name) {
    const err = new Error("Missing required fields: amount and customer (first_name,last_name)");
    err.statusCode = 400;
    throw err;
  }

  const orderid = `BDPG_${Date.now()}`;

  const payload = {
    orderid,
    mercid: process.env.BD_MERCHANT_ID,
    order_date: new Date().toISOString(),
    amount: Number(body.amount).toFixed(2),
    currency: body.currency || "356",
    ru: process.env.BD_RETURN_URL,
    itemcode: body.itemcode || "DIRECT",
    mandate_required: body.mandate_required || "N",
    customer: body.customer,
    device: body.device || {
      init_channel: "internet",
      ip: body.ip || "",
      user_agent: body.user_agent || "",
      accept_header: body.accept_header || ""
    }
  };

  // insert order
  await model.insertOrder({
    orderid,
    amount: payload.amount,
    customer: JSON.stringify(payload.customer),
    payload: payload,
    status: "INITIATED",
    traceid: null,
    created_at: new Date()
  });

  // call billdesk
  const clientId = process.env.BD_CLIENT_ID || process.env.BD_MERCHANT_ID;
  const encKey = process.env.BD_ENC_KEY;
  const sigKey = process.env.BD_SIGN_KEY;

  const result = await billdeskClient.callBilldesk({
    path: 'orders/create',
    payload,
    clientId,
    encKey,
    sigKey
  });

  await model.updateOrderByOrderId(orderid, {
    status: result.status || 'ACTIVE',
    bdorderid: result.bdorderid || null,
    raw_response: JSON.stringify(result),
    updated_at: new Date()
  });

  return {
    orderid,
    bdorderid: result.bdorderid || null,
    next_step: result.next_step || null,
    links: result.links || [],
    raw: result
  };
}

module.exports = { createOrder };
