#!/usr/bin/env tsx

import Database from "better-sqlite3";
import fs from "fs";
import path from "path";
import { MigrationRunner } from "../apps/service/src/migration-runner";

const args = process.argv.slice(2);
const command = args[0];

if (!command) {
  console.log("Usage: migrate <command>");
  console.log("Commands:");
  console.log("  up          - Apply all pending migrations");
  console.log("  create <name> - Create a new migration file");
  console.log("  status      - Show migration status");
  process.exit(1);
}

// Find project root
let projectRoot = process.cwd();
while (projectRoot !== path.dirname(projectRoot)) {
  if (fs.existsSync(path.join(projectRoot, "package.json"))) {
    try {
      const pkg = JSON.parse(
        fs.readFileSync(path.join(projectRoot, "package.json"), "utf-8")
      );
      if (pkg.name === "watch-finished-turbo") {
        break;
      }
    } catch (e) {
      // ignore
    }
  }
  projectRoot = path.dirname(projectRoot);
}

const dbPath = path.resolve(projectRoot, "data/database.db");
const migrationsDir = path.resolve(projectRoot, "data/migrations");

// Ensure directories exist
if (!fs.existsSync(path.dirname(dbPath))) {
  fs.mkdirSync(path.dirname(dbPath), { recursive: true });
}
if (!fs.existsSync(migrationsDir)) {
  fs.mkdirSync(migrationsDir, { recursive: true });
}

const db = new Database(dbPath);
const runner = new MigrationRunner(db, migrationsDir);

try {
  switch (command) {
    case "up":
      runner.applyPendingMigrations();
      break;

    case "create":
      const name = args[1];
      if (!name) {
        console.error("Migration name is required");
        process.exit(1);
      }
      runner.createMigration(name);
      break;

    case "status":
      runner.init();
      const applied = runner.getAppliedMigrations();
      const available = runner.getAvailableMigrations();
      const pending = available.filter((m) => !applied.includes(m));

      console.log("Migration Status:");
      console.log(`Applied: ${applied.length}`);
      console.log(`Available: ${available.length}`);
      console.log(`Pending: ${pending.length}`);

      if (pending.length > 0) {
        console.log("\nPending migrations:");
        pending.forEach((m) => console.log(`  - ${m}`));
      }
      break;

    default:
      console.error(`Unknown command: ${command}`);
      process.exit(1);
  }
} finally {
  db.close();
}
