import 'dotenv/config';
import { readdir } from 'node:fs/promises';
import path from 'node:path';
import { db } from '@/lib/db';
import { formTemplates } from '@/lib/db/schema';

const SEEDS_DIR = path.join(process.cwd(), 'seeds', 'forms');

async function seedForms() {
  const files = await readdir(SEEDS_DIR);
  const pdfs = files.filter(f => f.endsWith('.pdf'));

  if (pdfs.length === 0) {
    console.log('No PDF files found in seeds/forms/. Add PDFs downloaded from the SkySlope portal and re-run.');
    return;
  }

  let seeded = 0;
  for (const filename of pdfs) {
    const name = filename
      .replace(/\.pdf$/i, '')
      .replace(/[-_]/g, ' ')
      .replace(/\b\w/g, c => c.toUpperCase());

    await db.insert(formTemplates)
      .values({ name, filename })
      .onConflictDoUpdate({
        target: formTemplates.filename,
        set: { name, updatedAt: new Date() },
      });
    seeded++;
  }
  console.log(`Seeded ${seeded} forms into form_templates.`);
  process.exit(0);
}

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