/**
 * Production database cleanup + re-seed.
 * Truncates all tables (data only), then runs the seed to restore base data.
 *
 * Usage (from backend directory):
 *   node prisma/clean-and-seed.js
 *
 * Or: npm run db:clean-and-seed
 *
 * Ensure DATABASE_URL is set (e.g. production). Back up the DB before running.
 */

const { PrismaClient } = require('@prisma/client');
const { execSync } = require('child_process');
const path = require('path');

const prisma = new PrismaClient();

// All tables from schema (Prisma @@map names) – order does not matter with CASCADE
const TABLES = [
  'audit_logs',
  'approvals',
  'notifications',
  'custom_fields',
  'attachments',
  'notes',
  'activities',
  'campaigns',
  'project_expenses',
  'project_members',
  'tasks',
  'project_phases',
  'projects',
  'asset_maintenances',
  'assets',
  'warehouse_transfers',
  'inventory_movements',
  'inventory_items',
  'product_categories',
  'products',
  'warehouses',
  'invoices',
  'contracts',
  'cost_sheets',
  'quotes',
  'deals',
  'pipelines',
  'contact_relationships',
  'contact_categories',
  'contacts',
  'disciplinary_actions',
  'employee_trainings',
  'performance_evaluations',
  'commissions',
  'allowances',
  'salaries',
  'leaves',
  'attendances',
  'position_permissions',
  'positions',
  'departments',
  'employees',
  'users',
];

async function clean() {
  console.log('🧹 Truncating all tables...');
  const quoted = TABLES.map((t) => `"${t}"`).join(', ');
  await prisma.$executeRawUnsafe(
    `TRUNCATE TABLE ${quoted} RESTART IDENTITY CASCADE;`
  );
  console.log('✅ All tables truncated.');
}

async function main() {
  const env = process.env.NODE_ENV || 'development';
  if (process.env.DATABASE_URL?.includes('prod') || env === 'production') {
    console.log('⚠️  DATABASE_URL appears to be PRODUCTION. Ensure you have a backup.\n');
  }

  await clean();
  await prisma.$disconnect();

  console.log('\n🌱 Running seed...\n');
  const backendDir = path.resolve(__dirname, '..');
  execSync('node prisma/seed.js', {
    stdio: 'inherit',
    cwd: backendDir,
    env: process.env,
  });
  console.log('\n✅ Clean and seed completed.');
}

main().catch((e) => {
  console.error('❌ Error:', e);
  process.exit(1);
});
