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 archive 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 title = String(body.title ?? '').trim();
  const youtubeId = String(body.youtube_id ?? '').trim();

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

  const pool = getPool();
  await pool.query('INSERT INTO archive (title, youtube_id) VALUES (?, ?)', [title, youtubeId]);
  return NextResponse.json({ ok: true });
}
