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 updates: string[] = [];
  const values: unknown[] = [];

  if (body.question !== undefined) {
    updates.push('question = ?');
    values.push(String(body.question).trim());
  }
  if (body.answer !== undefined) {
    updates.push('answer = ?');
    values.push(String(body.answer).trim());
  }

  if (updates.length === 0) {
    return NextResponse.json({ error: 'No fields to update' }, { status: 400 });
  }

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

  const [rows] = await pool.query<RowDataPacket[]>('SELECT * FROM contact WHERE id = ?', [id]);
  return NextResponse.json({ item: rows[0] });
}

export async function DELETE(_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 pool = getPool();
  await pool.query('DELETE FROM contact WHERE id = ?', [id]);
  return NextResponse.json({ ok: true });
}
