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 p.id, p.player_key, p.player_name, p.description, p.image, p.character_id,
            c.name_id, c.name, c.name_jp
     FROM players p
     LEFT JOIN characters c ON c.id = p.character_id
     ORDER BY p.id ASC`
  );

  return NextResponse.json({ players: rows });
}

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

  const body = await request.json();
  const playerKey = String(body.player_key ?? '').trim();
  const playerName = String(body.player_name ?? '').trim();
  const description = String(body.description ?? '');
  const image = body.image != null ? String(body.image) : null;
  const characterId = parseInt(String(body.character_id), 10);

  if (!playerKey || !playerName || Number.isNaN(characterId)) {
    return NextResponse.json({ error: 'player_key, player_name, character_id required' }, { status: 400 });
  }

  const pool = getPool();
  await pool.query(
    `INSERT INTO players (player_key, player_name, description, image, character_id)
     VALUES (?, ?, ?, ?, ?)`,
    [playerKey, playerName, description, image, String(characterId)]
  );

  return NextResponse.json({ ok: true });
}
