// 모모유통 마이그레이션 실행 스크립트
// 사용법: node scripts/migrate-momo.mjs
// .env.development 또는 .env.production 의 DATABASE_URL 사용

import pg from "pg";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const envFile = process.env.NODE_ENV === "production" ? ".env.production" : ".env.development";
const envPath = path.join(__dirname, "..", envFile);
if (fs.existsSync(envPath)) {
  for (const line of fs.readFileSync(envPath, "utf-8").split(/\r?\n/)) {
    const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
    if (m) process.env[m[1]] ??= m[2].replace(/^["']|["']$/g, "");
  }
}

const dir = path.join(__dirname, "..", "db", "migrations");
const files = fs.readdirSync(dir).filter((f) => f.endsWith(".sql")).sort();
const conn = process.env.DATABASE_URL;
if (!conn) {
  console.error("DATABASE_URL 환경변수가 설정되지 않았습니다.");
  process.exit(1);
}

const client = new pg.Client({ connectionString: conn });
await client.connect();
console.log(`[migrate] DB connected. Running ${files.length} files...`);
for (const f of files) {
  const sql = fs.readFileSync(path.join(dir, f), "utf-8");
  console.log(`  → ${f}`);
  try {
    await client.query(sql);
  } catch (err) {
    console.error(`  ✖ ${f} 실패:`, err.message);
    await client.end();
    process.exit(1);
  }
}
console.log("[migrate] ✔ 완료");
await client.end();
