// billdeskpg/models/billdesk.model.js
const pool = require('../../db/pool');

module.exports = {
  insertOrder: async (order) => {
    const sql = `INSERT INTO billdesk_orders (orderid, amount, customer, payload, status, traceid, created_at)
      VALUES (?, ?, ?, ?, ?, ?, ?)`;
    const params = [
      order.orderid,
      order.amount,
      order.customer || null,
      order.payload ? JSON.stringify(order.payload) : null,
      order.status || 'INITIATED',
      order.traceid || null,
      order.created_at || new Date()
    ];
    const [res] = await pool.execute(sql, params);
    return res;
  },

  updateOrderByOrderId: async (orderid, updates = {}) => {
    const fields = [];
    const params = [];

    if (updates.status !== undefined) { fields.push('status = ?'); params.push(updates.status); }
    if (updates.bdorderid !== undefined) { fields.push('bdorderid = ?'); params.push(updates.bdorderid); }
    if (updates.raw_response !== undefined) { fields.push('raw_response = ?'); params.push(updates.raw_response); }
    if (updates.traceid !== undefined) { fields.push('traceid = ?'); params.push(updates.traceid); }
    if (updates.updated_at !== undefined) { fields.push('updated_at = ?'); params.push(updates.updated_at); }

    if (fields.length === 0) return null;
    const sql = `UPDATE billdesk_orders SET ${fields.join(', ')} WHERE orderid = ?`;
    params.push(orderid);
    const [result] = await pool.execute(sql, params);
    return result;
  },

  getOrderByOrderId: async (orderid) => {
    const [rows] = await pool.execute('SELECT * FROM billdesk_orders WHERE orderid = ?', [orderid]);
    return rows && rows[0];
  }
};
