
import dotenv from 'dotenv';
import fs from 'fs/promises';
import postgres from 'postgres';
import path from 'path';

async function main() {
  dotenv.config({ path: path.resolve(process.cwd(), '.env.local') });

  const url = process.env.DATABASE_URL;
  if (!url) {
    console.error('DATABASE_URL is not set in .env.local');
    process.exit(1);
  }

  const filePath = path.resolve(process.cwd(), 'lib/db/sql/policies.sql');
  let sqlText = '';
  try {
    sqlText = await fs.readFile(filePath, 'utf8');
  } catch {
    console.error('Cannot read SQL file:', filePath);
    process.exit(1);
  }

  const statements = sqlText
    .split(';')
    .map((s) => s.trim())
    .filter((s) => s.length > 0 && !s.startsWith('--'));

  const sql = postgres(url, { max: 1 });

  console.log(`🔒  Applying ${statements.length} RLS statements…\n`);

  let ok = 0;
  let skipped = 0;

  for (const stmt of statements) {
    const preview = stmt.replace(/\s+/g, ' ').substring(0, 70);
    try {
      await sql.unsafe(stmt);
      console.log(`   ✓  ${preview}`);
      ok++;
    } catch (err) {
      const msg = (err as Error).message ?? '';
      if (/already exists|does not exist/i.test(msg)) {
        console.warn(`   ⚠  Skipped (${msg.split('\n')[0].trim()})`);
        skipped++;
      } else {
        console.error(`\n❌  Failed on:\n    ${preview}`);
        console.error(`    Error: ${msg}`);
        await sql.end({ timeout: 3 });
        process.exit(1);
      }
    }
  }

  await sql.end({ timeout: 3 });
  console.log(`\n Done — ${ok} applied, ${skipped} skipped.\n`);
}

main();