import { NextRequest, NextResponse } from 'next/server';
import { isAdminTokenValue, isGuestTokenValue, getGuestFromRequest, verifyAdminToken } from '@/lib/auth/tokens';
import { ADM_COOKIE, USR_COOKIE, buildCookie, isSecureCookie } from '@/lib/auth/cookies';

const ONE_YEAR = 60 * 60 * 24 * 365;

export async function POST(request: NextRequest) {
  const body = await request.json().catch(() => ({}));
  const { adm, usr } = body as { adm?: string; usr?: string };

  const headers = new Headers();
  const secure = isSecureCookie(request);
  const cookies: string[] = [];
  let role: 'admin' | 'guest' | 'none' = 'none';
  let guestId: string | null = null;

  if (adm) {
    if (!isAdminTokenValue(adm)) {
      return NextResponse.json({ error: 'Invalid admin token' }, { status: 401 });
    }
    cookies.push(buildCookie(ADM_COOKIE, adm, secure, ONE_YEAR));
    role = 'admin';
  }

  if (usr) {
    const guest = await isGuestTokenValue(usr);
    if (!guest) {
      return NextResponse.json({ error: 'Invalid guest token' }, { status: 401 });
    }
    cookies.push(buildCookie(USR_COOKIE, usr, secure, ONE_YEAR));
    if (role !== 'admin') role = 'guest';
    guestId = guest.id;
  }

  if (cookies.length === 0) {
    return NextResponse.json({ error: 'No token provided' }, { status: 400 });
  }

  for (const c of cookies) headers.append('Set-Cookie', c);
  return NextResponse.json({ success: true, role, guestId }, { headers });
}

export async function GET(request: NextRequest) {
  const isAdmin = verifyAdminToken(request);
  const guest = await getGuestFromRequest(request);

  if (isAdmin) return NextResponse.json({ role: 'admin', guest: guest ? { id: guest.id, name: guest.name } : null });
  if (guest) return NextResponse.json({ role: 'guest', guest: { id: guest.id, name: guest.name } });
  return NextResponse.json({ role: 'none' });
}
