import { NextResponse } from 'next/server';
import type { RowDataPacket } from 'mysql2';

import { requireAdminApi } from '@/lib/auth/apiAuth';
import { getPool } from '@/lib/db';

export const dynamic = 'force-dynamic';

type Ctx = { params: Promise<{ id: string }> };

export async function PATCH(request: Request, context: Ctx) {
  const auth = await requireAdminApi();
  if (!auth.ok) {
    return auth.response;
  }

  const { id: idParam } = await context.params;
  const id = parseInt(idParam, 10);
  if (Number.isNaN(id)) {
    return NextResponse.json({ error: 'Invalid id' }, { status: 400 });
  }

  const body = await request.json();
  const isApproved = typeof body.is_approved === 'boolean' ? body.is_approved : undefined;
  const isAdmin = typeof body.is_admin === 'boolean' ? body.is_admin : undefined;

  if (isApproved === undefined && isAdmin === undefined) {
    return NextResponse.json({ error: 'No changes' }, { status: 400 });
  }

  const pool = getPool();

  if (id === auth.user.id && isApproved === false) {
    return NextResponse.json({ error: 'Cannot revoke your own approval' }, { status: 400 });
  }
  if (id === auth.user.id && isAdmin === false) {
    return NextResponse.json({ error: 'Cannot remove your own admin role' }, { status: 400 });
  }

  const updates: string[] = [];
  const values: unknown[] = [];
  if (isApproved !== undefined) {
    updates.push('is_approved = ?');
    values.push(isApproved ? 1 : 0);
  }
  if (isAdmin !== undefined) {
    updates.push('is_admin = ?');
    values.push(isAdmin ? 1 : 0);
  }
  values.push(id);

  await pool.query(
    `UPDATE admin_users SET ${updates.join(', ')} WHERE id = ?`,
    values
  );

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

  return NextResponse.json({ user: rows[0] ?? null });
}
