// Seeds the four pillars and (optionally) the admin/JT account.
// Run: npm run seed
// To create the admin, set ADMIN_EMAIL and ADMIN_PASSWORD in .env first.
import { ulid } from 'ulid';
import { execute, queryOne } from './client.js';
import { hashPassword } from '../utils/password.js';

const now = () => Math.floor(Date.now() / 1000);

const PILLARS = [
  {
    slug: 'foundation',
    title: 'Foundation',
    subtitle: 'The four-box business model, your offer, positioning, and the operating fundamentals most owners skip.',
  },
  {
    slug: 'market-and-revenue',
    title: 'Market and Revenue',
    subtitle: 'Lead generation, pricing, customer profiling, offers that sell, and conversion.',
  },
  {
    slug: 'operations-and-systems',
    title: 'Operations and Systems',
    subtitle: 'SOPs, delegation, hiring scorecards, KPI dashboards, and the operating cadence.',
  },
  {
    slug: 'scale-and-exit',
    title: 'Scale and Exit',
    subtitle: 'Capacity planning, financial command, sellability, and exit.',
  },
];

async function seedPillars() {
  let sort = 0;
  for (const p of PILLARS) {
    const existing = await queryOne(`SELECT id FROM pillars WHERE slug = ?`, [p.slug]);
    if (existing) {
      console.log('pillar exists ', p.slug);
      sort += 1;
      continue;
    }
    await execute(
      `INSERT INTO pillars (id, slug, title, subtitle, sort, created_at) VALUES (?, ?, ?, ?, ?, ?)`,
      [ulid(), p.slug, p.title, p.subtitle, sort, now()]
    );
    console.log('seeded pillar', p.slug);
    sort += 1;
  }
}

async function seedAdmin() {
  const email = (process.env.ADMIN_EMAIL || 'jt@notebookofacoo.com').toLowerCase();
  const password = process.env.ADMIN_PASSWORD;
  const existing = await queryOne(`SELECT id FROM users WHERE email = ?`, [email]);
  if (existing) {
    console.log('admin exists  ', email);
    return;
  }
  if (!password) {
    console.log('skip admin: set ADMIN_PASSWORD in .env to create the admin (JT) account');
    return;
  }
  await execute(
    `INSERT INTO users (id, email, password_hash, display_name, role, created_at, updated_at)
     VALUES (?, ?, ?, 'JT', 'admin', ?, ?)`,
    [ulid(), email, await hashPassword(password), now(), now()]
  );
  console.log('seeded admin ', email);
}

async function run() {
  await seedPillars();
  await seedAdmin();
  console.log('seed complete');
  process.exit(0);
}

run().catch((err) => {
  console.error('seed failed:', err);
  process.exit(1);
});
