/**
 * Áp dụng migration lên cơ sở dữ liệu đang cấu hình (PGlite hoặc Postgres thật).
 *
 *   npm run db:generate   → sinh SQL vào thư mục ./drizzle sau khi sửa schema
 *   npm run db:push       → áp dụng SQL đó lên database
 */
import "./load-env";
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";

const MIGRATIONS_DIR = join(process.cwd(), "drizzle");

async function main() {
  const driver = process.env.DB_DRIVER ?? "pglite";

  const files = readdirSync(MIGRATIONS_DIR)
    .filter((f) => f.endsWith(".sql"))
    .sort();

  if (files.length === 0) {
    console.error("Chưa có file migration nào. Chạy `npm run db:generate` trước.");
    process.exit(1);
  }

  // Drizzle ngăn cách các câu lệnh bằng dấu hiệu này trong file SQL sinh ra.
  const STATEMENT_BREAK = "--> statement-breakpoint";

  const run = async (exec: (sql: string) => Promise<unknown>) => {
    for (const file of files) {
      const sql = readFileSync(join(MIGRATIONS_DIR, file), "utf8");
      const statements = sql
        .split(STATEMENT_BREAK)
        .map((s) => s.trim())
        .filter(Boolean);

      for (const statement of statements) {
        try {
          await exec(statement);
        } catch (error) {
          const message = error instanceof Error ? error.message : String(error);
          // Chạy lại push trên database đã có sẵn bảng là trường hợp bình thường.
          if (/already exists/i.test(message)) continue;
          console.error(`\nLỗi khi chạy câu lệnh trong ${file}:\n${statement}\n`);
          throw error;
        }
      }
      console.log(`  ✓ ${file} (${statements.length} câu lệnh)`);
    }
  };

  if (driver === "pg") {
    const { Pool } = await import("pg");
    const pool = new Pool({ connectionString: process.env.DATABASE_URL });
    console.log("Áp dụng migration lên Postgres…");
    await run((sql) => pool.query(sql));
    await pool.end();
  } else {
    const { PGlite } = await import("@electric-sql/pglite");
    const dir = process.env.PGLITE_DIR ?? "./.pgdata";
    const client = new PGlite(dir);
    console.log(`Áp dụng migration lên PGlite (${dir})…`);
    await run((sql) => client.exec(sql));
    await client.close();
  }

  console.log("Xong. Cơ sở dữ liệu đã sẵn sàng.\n");
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
