#!/usr/bin/env node
const { pool, query } = require("./config/database");
const fs = require("fs");
const path = require("path");

async function applyMigration() {
  console.log("🔧 Applying Database Fixes...\n");

  try {
    // Read the migration file
    const migrationPath = path.join(
      __dirname,
      "migrations",
      "006_database_fixes.sql"
    );
    const migrationSQL = fs.readFileSync(migrationPath, "utf8");

    console.log("📄 Running migration: 006_database_fixes.sql");
    console.log("─".repeat(60));

    // Execute the migration
    await query(migrationSQL);

    console.log("\n✅ Migration applied successfully!");
    console.log("\n📊 Verification:");
    console.log("─".repeat(60));

    // Verify the changes
    const fkResult = await query(`
      SELECT COUNT(*) as fk_count
      FROM information_schema.table_constraints
      WHERE constraint_type = 'FOREIGN KEY'
        AND table_schema = 'public'
    `);
    console.log(`   Foreign keys: ${fkResult.rows[0].fk_count}`);

    const indexResult = await query(`
      SELECT COUNT(*) as index_count
      FROM pg_indexes
      WHERE schemaname = 'public'
        AND tablename IN ('products', 'product_images', 'portfolioprojects', 'blogposts', 'pages')
    `);
    console.log(`   Indexes (main tables): ${indexResult.rows[0].index_count}`);

    const uniqueResult = await query(`
      SELECT COUNT(*) as unique_count
      FROM information_schema.table_constraints
      WHERE constraint_type = 'UNIQUE'
        AND table_schema = 'public'
        AND table_name IN ('products', 'blogposts', 'pages')
    `);
    console.log(`   Unique constraints: ${uniqueResult.rows[0].unique_count}`);

    console.log("\n✅ Database fixes complete!");
  } catch (error) {
    console.error("❌ Error applying migration:", error.message);
    console.error(error);
    process.exit(1);
  } finally {
    await pool.end();
  }
}

applyMigration();
