'use strict';

const fs = require('node:fs/promises');
const path = require('node:path');
const { randomUUID } = require('node:crypto');
const config = require('../src/config');
const { pool, withTransaction } = require('../src/db');
const { calculateLine, riyadhDate } = require('../src/utils');

async function main() {
  if (!process.argv.includes('--yes')) {
    throw new Error('هذا الأمر يضيف عهدة فعلية من الملف المرجعي. أعد التشغيل مع --yes للتأكيد.');
  }
  const rows = JSON.parse(await fs.readFile(path.join(config.rootDir, 'database/reference-custody.json'), 'utf8'));
  const [products] = await pool.query('SELECT id, sort_order FROM products ORDER BY sort_order, id');
  const productByOrder = new Map(products.map((product) => [product.sort_order, product.id]));
  const dateArg = process.argv.find((value) => value.startsWith('--date='));
  const custodyDate = dateArg ? dateArg.slice(7) : riyadhDate();

  const items = rows.map((raw, index) => ({
    productId: productByOrder.get(index + 1) || null,
    lineNo: index + 1,
    productName: raw.productName,
    unitName: raw.unitName || null,
    note: raw.note || null,
    ...calculateLine(raw),
  }));
  const totalCost = items.reduce((sum, item) => sum + (item.totalCost || 0), 0);

  const result = await withTransaction(async (connection) => {
    const [insert] = await connection.execute(
      `INSERT INTO custodies
       (custody_number, custody_date, created_by_user_id, created_by_name, created_by_category, line_count, total_cost)
       VALUES (?, ?, NULL, 'استيراد الملف المرجعي', 'نظام', ?, ?)`,
      [`TMP-${randomUUID()}`, custodyDate, items.length, totalCost],
    );
    const number = `VEG-${custodyDate.replaceAll('-', '')}-${String(insert.insertId).padStart(6, '0')}`;
    await connection.execute('UPDATE custodies SET custody_number = ? WHERE id = ?', [number, insert.insertId]);
    const placeholders = items.map(() => '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').join(',');
    const params = items.flatMap((item) => [
      insert.insertId, item.productId, item.lineNo, item.productName, item.unitName,
      item.quantity, item.packSize, item.totalUnits, item.unitCost, item.totalCost,
      item.costPerUnit, item.salePrice, item.note,
    ]);
    await connection.query(
      `INSERT INTO custody_items
       (custody_id, product_id, line_no, product_name, unit_name, quantity, pack_size,
        total_units, unit_cost, total_cost, cost_per_unit, sale_price, note)
       VALUES ${placeholders}`,
      params,
    );
    return { id: insert.insertId, number };
  });
  console.log(`تم استيراد العهدة المرجعية: ${result.number}`);
}

main()
  .catch((error) => {
    console.error('فشل الاستيراد:', error.message);
    process.exitCode = 1;
  })
  .finally(() => pool.end());
