/**
 * Migration script: server-settings.json → PostgreSQL server_config table
 *
 * Usage: bun run scripts/migrate-server-settings-to-pg.ts
 */

import { join } from 'node:path';
import { writeServerSettings } from 'officerdb';

const DATA_PATH = process.env.DATA_PATH ?? join(process.cwd(), 'data');
const settingsPath = join(DATA_PATH, 'server-settings', 'server-settings.json');

async function migrate() {
  console.log(`[migrate] Reading ${settingsPath}`);

  const file = Bun.file(settingsPath);
  if (!(await file.exists())) {
    console.log('[migrate] No server-settings.json found. Done.');
    process.exit(0);
  }

  let settings: Record<string, unknown>;
  try {
    settings = await file.json();
  } catch {
    console.log('[migrate] Could not parse server-settings.json. Done.');
    process.exit(0);
  }

  const keys = Object.keys(settings);
  console.log(`[migrate] Found ${keys.length} keys: ${keys.join(', ')}`);

  await writeServerSettings(settings);
  console.log('[migrate] Written to server_config table.');
  console.log('[migrate] Done!');
  process.exit(0);
}

migrate().catch((err) => {
  console.error('[migrate] Failed:', err);
  process.exit(1);
});
