/**
 * Creates the first admin (superadmin) from BOOTSTRAP_ADMIN_* env vars.
 * PLANNING.md §3 diagram: "first admin user, from env — never a hardcoded
 * password." Step 4 builds real auth (login, invite, phone normalisation);
 * this only needs to get one usable account into the table.
 *
 * Safe to re-run: if the phone already exists the seed is a no-op and never
 * touches the stored password. If the env vars are unset it warns and returns,
 * so `npm run seed` still succeeds for the category seed.
 */
import type { Knex } from 'knex';
import { newId } from '../src/lib/ulid';
import { normalizePhone } from '../src/lib/phone';
import { hashPassword } from '../src/modules/auth/password.service';
import { env } from '../src/env';

export async function seed(knex: Knex): Promise<void> {
  const name = env.BOOTSTRAP_ADMIN_NAME;
  const rawPhone = env.BOOTSTRAP_ADMIN_PHONE;
  const password = env.BOOTSTRAP_ADMIN_PASSWORD;

  if (!name || !rawPhone || !password) {
    console.warn(
      '[seed] bootstrap admin skipped — set BOOTSTRAP_ADMIN_NAME / BOOTSTRAP_ADMIN_PHONE / BOOTSTRAP_ADMIN_PASSWORD in .env',
    );
    return;
  }

  const { e164, display } = normalizePhone(rawPhone);

  const existing = await knex('admin_users').where({ phone: e164 }).first();
  if (existing) {
    console.log('[seed] bootstrap admin already present — password left untouched');
    return;
  }

  await knex('admin_users').insert({
    id: newId(),
    phone: e164,
    phone_display: display,
    email: env.BOOTSTRAP_ADMIN_EMAIL ?? null,
    name,
    password_hash: await hashPassword(password),
    role: 'superadmin',
    status: 'active',
  });
  console.log('[seed] bootstrap superadmin created');
}
