'use strict';

const fs = require('node:fs/promises');
const path = require('node:path');
const { pool } = require('../src/db');

const INSERT_ORDER = ['admins', 'users', 'user_permissions', 'products', 'custodies', 'custody_items', 'audit_logs'];
const DELETE_ORDER = ['audit_logs', 'custody_items', 'custodies', 'products', 'user_permissions', 'user_sessions', 'users', 'admin_sessions', 'admins'];

function arg(name) {
  const prefix = `--${name}=`;
  const value = process.argv.find((item) => item.startsWith(prefix));
  return value ? value.slice(prefix.length) : null;
}

async function main() {
  const file = arg('file');
  if (!file || !process.argv.includes('--yes')) {
    throw new Error('الاستخدام: npm run restore -- --file=/path/backup.json --yes [--force]');
  }
  const backup = JSON.parse(await fs.readFile(path.resolve(file), 'utf8'));
  if (backup.format !== 'ayman-mark-vegetable-backup' || !backup.tables) throw new Error('ملف النسخة الاحتياطية غير معتمد.');

  const connection = await pool.getConnection();
  try {
    if (!process.argv.includes('--force')) {
      const [[row]] = await connection.query('SELECT (SELECT COUNT(*) FROM users) + (SELECT COUNT(*) FROM custodies) AS count');
      if (row.count > 0) throw new Error('قاعدة البيانات ليست فارغة. أضف --force فقط بعد أخذ نسخة احتياطية حالية.');
    }

    await connection.query('SET FOREIGN_KEY_CHECKS = 0');
    await connection.beginTransaction();
    for (const table of DELETE_ORDER) await connection.query(`DELETE FROM \`${table}\``);

    for (const table of INSERT_ORDER) {
      let rows = backup.tables[table] || [];
      if (!rows.length) continue;

      if (table === 'custodies') {
        rows = rows.map((row) => ({
          ...row,
          custody_name: row.custody_name || `عهدة ${String(row.custody_date || '').slice(0, 10)}`,
        }));
      }

      const columns = Object.keys(rows[0]);
      const placeholders = rows.map(() => `(${columns.map(() => '?').join(',')})`).join(',');
      const values = rows.flatMap((row) => columns.map((column) => {
        const value = row[column];
        if (column === 'details_json' && value && typeof value === 'object') return JSON.stringify(value);
        return value;
      }));
      await connection.query(
        `INSERT INTO \`${table}\` (${columns.map((column) => `\`${column}\``).join(',')}) VALUES ${placeholders}`,
        values,
      );
    }
    await connection.commit();
    await connection.query('SET FOREIGN_KEY_CHECKS = 1');
    console.log(`تمت استعادة النسخة الاحتياطية: ${path.resolve(file)}`);
  } catch (error) {
    await connection.rollback().catch(() => {});
    await connection.query('SET FOREIGN_KEY_CHECKS = 1').catch(() => {});
    throw error;
  } finally {
    connection.release();
  }
}

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