import type { Handler } from 'hono';
import { getUserCount, createUser } from 'officerdb';
import argon2 from 'argon2';
import * as errors from '@@/custom-errors';
import { validatePassword } from './validate-password';
import { validateUsername } from './validate-username';
import { provisionUserEnvironment } from '../users/provision';

// Single-step bootstrap for the one account Officer supports: the server owner is created directly as
// active, with no email-verification round-trip. Gated to an empty user table.
export const bootstrapHandler: Handler = async function (ctx) {
  const body = ctx.get('body');

  const userCount = await getUserCount();
  if (userCount > 0) throw errors.FORBIDDEN('Registration is closed');

  const email = body.email as string;
  const name = body.name as string;
  const username = body.username as string;
  const password = body.password as string;
  const confirmPassword = body.confirmPassword as string;

  if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    throw errors.BAD_REQUEST('Invalid email address');
  }
  if (!name || !name.trim()) throw errors.BAD_REQUEST('Name is required');
  const validUsername = validateUsername(username);
  validatePassword(password);
  if (password !== confirmPassword) throw errors.BAD_REQUEST('Passwords do not match');

  const passwordHash = await argon2.hash(password);

  const user = await createUser({
    email,
    password: passwordHash,
    name: name.trim(),
    username: validUsername,
    status: 'Active',
  });

  // Provision the super admin's environment (DATA_PATH/<email> + configs) on creation. This is the only
  // account-creation flow for a single-user platform, and nothing else provisions the first user.
  // Fire-and-forget, mirroring verifyHandler.
  provisionUserEnvironment(user.email, user.username ?? validUsername).catch((err) => {
    console.error('[bootstrap] failed to provision super admin environment:', err);
  });

  return ctx.json({ ok: true });
};
