#!/usr/bin/env node
/**
 * Database Migration Runner
 * Applies SQL migration files to the database
 */

const fs = require("fs");
const path = require("path");
const { Pool } = require("pg");
require("dotenv").config();

const pool = new Pool({
  host: process.env.DB_HOST || "localhost",
  port: process.env.DB_PORT || 5432,
  database: process.env.DB_NAME || "skyartshop",
  user: process.env.DB_USER || "skyartapp",
  password: process.env.DB_PASSWORD,
});

async function applyMigration(filePath) {
  const client = await pool.connect();

  try {
    console.log(`\n📁 Reading migration: ${path.basename(filePath)}`);
    const sql = fs.readFileSync(filePath, "utf8");

    console.log("🔄 Applying migration...");
    await client.query("BEGIN");
    await client.query(sql);
    await client.query("COMMIT");

    console.log("✅ Migration applied successfully!\n");
  } catch (error) {
    await client.query("ROLLBACK");
    console.error("❌ Migration failed:", error.message);
    console.error("\nError details:", error);
    process.exit(1);
  } finally {
    client.release();
  }
}

async function main() {
  const migrationFile = process.argv[2];

  if (!migrationFile) {
    console.error("Usage: node apply-migration.js <migration-file.sql>");
    process.exit(1);
  }

  const fullPath = path.resolve(migrationFile);

  if (!fs.existsSync(fullPath)) {
    console.error(`Migration file not found: ${fullPath}`);
    process.exit(1);
  }

  await applyMigration(fullPath);
  await pool.end();
}

main().catch((error) => {
  console.error("Fatal error:", error);
  process.exit(1);
});
