const { query } = require("./config/database");

async function runMigration() {
  try {
    console.log("Running migration 004: Enhance color variants...");

    // Check current user
    const userResult = await query("SELECT current_user");
    console.log("Current database user:", userResult.rows[0].current_user);

    // Check table owner
    const ownerResult = await query(`
      SELECT tableowner FROM pg_tables 
      WHERE tablename = 'product_images'
    `);
    console.log("Table owner:", ownerResult.rows[0]?.tableowner);

    // Check if columns exist
    const columnsResult = await query(`
      SELECT column_name FROM information_schema.columns 
      WHERE table_name = 'product_images' 
      AND column_name IN ('color_code', 'variant_price', 'variant_stock')
    `);
    console.log(
      "Existing columns:",
      columnsResult.rows.map((r) => r.column_name)
    );

    if (columnsResult.rows.length === 3) {
      console.log("✓ All columns already exist - no migration needed!");
      process.exit(0);
      return;
    }

    console.log("\nPlease run this SQL manually as postgres superuser:");
    console.log("---");
    console.log(`
ALTER TABLE product_images 
ADD COLUMN IF NOT EXISTS color_code VARCHAR(7),
ADD COLUMN IF NOT EXISTS variant_price DECIMAL(10,2),
ADD COLUMN IF NOT EXISTS variant_stock INTEGER DEFAULT 0;

CREATE INDEX IF NOT EXISTS idx_product_images_color_code 
ON product_images(color_code);
    `);
    console.log("---");

    process.exit(1);
  } catch (error) {
    console.error("✗ Error:", error.message);
    process.exit(1);
  }
}

runMigration();
