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.title !== undefined) {
    updates.push('title = ?');
    values.push(String(body.title).trim());
  }
  if (body.youtube_id !== undefined) {
    updates.push('youtube_id = ?');
    values.push(String(body.youtube_id).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 archive SET ${updates.join(', ')} WHERE id = ?`, values);

  const [rows] = await pool.query<RowDataPacket[]>('SELECT * FROM archive 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 archive WHERE id = ?', [id]);
  return NextResponse.json({ ok: true });
}
