import { NextResponse } from 'next/server';

import { verifyPassword } from '@/lib/auth/password';
import { createSession } from '@/lib/auth/session';
import { getPool } from '@/lib/db';
import type { RowDataPacket } from 'mysql2';

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 || !password) {
      return NextResponse.json({ error: 'Email and password required' }, { status: 400 });
    }

    const pool = getPool();
    const [rows] = await pool.query<RowDataPacket[]>(
      'SELECT id, email, password_hash, is_approved, is_admin FROM admin_users WHERE email = ?',
      [email]
    );

    if (rows.length === 0) {
      return NextResponse.json({ error: 'Invalid email or password' }, { status: 401 });
    }

    const row = rows[0];
    const ok = verifyPassword(password, row.password_hash as string);
    if (!ok) {
      return NextResponse.json({ error: 'Invalid email or password' }, { status: 401 });
    }

    if (!row.is_approved) {
      return NextResponse.json(
        { error: 'Your account is not approved yet.', code: 'PENDING_APPROVAL' },
        { status: 403 }
      );
    }

    await createSession(row.id as number);

    return NextResponse.json({
      ok: true,
      user: {
        id: row.id,
        email: row.email,
        is_approved: Boolean(row.is_approved),
        is_admin: Boolean(row.is_admin),
      },
    });
  } catch (e) {
    console.error(e);
    return NextResponse.json({ error: 'Login failed' }, { status: 500 });
  }
}
