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';

export async function GET() {
  const auth = await requireAdminApi();
  if (!auth.ok) {
    return auth.response;
  }

  const pool = getPool();
  const [rows] = await pool.query<RowDataPacket[]>('SELECT * FROM contact ORDER BY id ASC');
  return NextResponse.json({ items: rows });
}

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

  const body = await request.json();
  const question = String(body.question ?? '').trim();
  const answer = String(body.answer ?? '').trim();

  if (!question || !answer) {
    return NextResponse.json({ error: 'question and answer required' }, { status: 400 });
  }

  const pool = getPool();
  await pool.query('INSERT INTO contact (question, answer) VALUES (?, ?)', [question, answer]);
  return NextResponse.json({ ok: true });
}
