import { readFile } from 'node:fs/promises';
import path from 'node:path';
import pg from 'pg';

const { Pool } = pg;
const contentPath = process.argv[2]
  ? path.resolve(process.argv[2])
  : path.resolve('deploy-data', 'homepage-content.json');
const connectionString = process.env.DATABASE_URL;

if (!connectionString) {
  throw new Error('DATABASE_URL is required for homepage content sync.');
}

const rawContent = await readFile(contentPath, 'utf8');
const homepageContent = JSON.parse(rawContent);
const pool = new Pool({ connectionString });

try {
  await pool.query(`
    create table if not exists site_content (
      key text primary key,
      value jsonb not null,
      updated_at timestamptz not null default now()
    )
  `);

  await pool.query(
    `
      insert into site_content (key, value)
      values ($1, $2::jsonb)
      on conflict (key)
      do update set value = excluded.value, updated_at = now()
    `,
    ['homepage', JSON.stringify(homepageContent)]
  );

  console.log(`[content-sync] Synced homepage content from ${contentPath}`);
} finally {
  await pool.end();
}
