import { NextResponse } from 'next/server';

import { hashPassword } from '@/lib/auth/password';
import { getPool } from '@/lib/db';

export const dynamic = 'force-dynamic';

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const email = typeof body.email === 'string' ? body.email.trim().toLowerCase() : '';
    const password = typeof body.password === 'string' ? body.password : '';

    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      return NextResponse.json({ error: 'Valid email is required' }, { status: 400 });
    }
    if (password.length < 8) {
      return NextResponse.json({ error: 'Password must be at least 8 characters' }, { status: 400 });
    }

    const passwordHash = hashPassword(password);
    const pool = getPool();
    await pool.query(
      `INSERT INTO admin_users (email, password_hash, is_approved, is_admin) VALUES (?, ?, 0, 0)`,
      [email, passwordHash]
    );

    return NextResponse.json({ ok: true, message: 'Registration submitted. Wait for an administrator to approve your account.' });
  } catch (e: unknown) {
    const code = (e as { code?: string })?.code;
    if (code === 'ER_DUP_ENTRY') {
      return NextResponse.json({ error: 'Email already registered' }, { status: 409 });
    }
    console.error(e);
    return NextResponse.json({ error: 'Registration failed' }, { status: 500 });
  }
}
