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

async function checkDatabase() {
  console.log("🔍 Checking Database Status...\n");

  try {
    // 1. Check connection
    console.log("1️⃣ Testing Connection...");
    const connResult = await query(
      "SELECT NOW() as time, current_database() as db"
    );
    console.log(`✅ Connected to: ${connResult.rows[0].db}`);
    console.log(`⏰ Server time: ${connResult.rows[0].time}\n`);

    // 2. List all tables
    console.log("2️⃣ Listing Tables...");
    const tablesResult = await query(`
      SELECT tablename 
      FROM pg_tables 
      WHERE schemaname = 'public' 
      ORDER BY tablename
    `);
    console.log(`📋 Tables (${tablesResult.rows.length}):`);
    tablesResult.rows.forEach((row) => console.log(`   - ${row.tablename}`));
    console.log();

    // 3. Check row counts
    console.log("3️⃣ Checking Row Counts...");
    const countResult = await query(`
      SELECT 
        (SELECT COUNT(*) FROM products) as products,
        (SELECT COUNT(*) FROM product_images) as product_images,
        (SELECT COUNT(*) FROM portfolioprojects) as portfolioprojects,
        (SELECT COUNT(*) FROM blogposts) as blogposts,
        (SELECT COUNT(*) FROM pages) as pages,
        (SELECT COUNT(*) FROM adminusers) as adminusers,
        (SELECT COUNT(*) FROM uploads) as uploads,
        (SELECT COUNT(*) FROM media_folders) as media_folders,
        (SELECT COUNT(*) FROM site_settings) as site_settings
    `);
    console.log("📊 Row counts:");
    Object.entries(countResult.rows[0]).forEach(([table, count]) => {
      console.log(`   ${table.padEnd(20)}: ${count}`);
    });
    console.log();

    // 4. Check for missing columns
    console.log("4️⃣ Checking Product Columns...");
    const productCols = await query(`
      SELECT column_name, data_type 
      FROM information_schema.columns 
      WHERE table_name = 'products'
      ORDER BY ordinal_position
    `);
    console.log(`📝 Products table has ${productCols.rows.length} columns`);

    // 5. Check indexes
    console.log("\n5️⃣ Checking Indexes...");
    const indexResult = await query(`
      SELECT 
        tablename,
        COUNT(*) as index_count
      FROM pg_indexes 
      WHERE schemaname = 'public'
      GROUP BY tablename
      ORDER BY tablename
    `);
    console.log("🔍 Index counts:");
    indexResult.rows.forEach((row) => {
      console.log(`   ${row.tablename.padEnd(25)}: ${row.index_count} indexes`);
    });
    console.log();

    // 6. Check foreign keys
    console.log("6️⃣ Checking Foreign Keys...");
    const fkResult = await query(`
      SELECT
        tc.table_name,
        kcu.column_name,
        ccu.table_name AS foreign_table,
        rc.delete_rule
      FROM information_schema.table_constraints AS tc
      JOIN information_schema.key_column_usage AS kcu
        ON tc.constraint_name = kcu.constraint_name
      JOIN information_schema.constraint_column_usage AS ccu
        ON ccu.constraint_name = tc.constraint_name
      JOIN information_schema.referential_constraints AS rc
        ON tc.constraint_name = rc.constraint_name
      WHERE tc.constraint_type = 'FOREIGN KEY'
        AND tc.table_schema = 'public'
      ORDER BY tc.table_name
    `);
    console.log(`🔗 Foreign keys (${fkResult.rows.length}):`);
    fkResult.rows.forEach((row) => {
      console.log(
        `   ${row.table_name}.${row.column_name} → ${row.foreign_table} (${row.delete_rule})`
      );
    });
    console.log();

    console.log("✅ Database check complete!");
  } catch (error) {
    console.error("❌ Error:", error.message);
  } finally {
    await pool.end();
  }
}

checkDatabase();
