import type { APIRoute } from 'astro';
import { moderateEntry } from '../../../lib/guestbook';
import { getSession, SESSION_COOKIE } from '../../../lib/auth';

export const prerender = false;

export const POST: APIRoute = async ({ request, cookies }) => {
  const sessionId = cookies.get(SESSION_COOKIE)?.value;
  const session = sessionId ? getSession(sessionId) : undefined;

  if (!session) {
    return new Response(null, { status: 303, headers: { Location: '/admin/login' } });
  }

  let formData: FormData;
  try {
    formData = await request.formData();
  } catch {
    return new Response(null, { status: 303, headers: { Location: '/admin' } });
  }

  const id = parseInt(String(formData.get('id') ?? ''), 10);
  const action = String(formData.get('action') ?? '');
  const note = String(formData.get('note') ?? '').trim() || null;

  if (isNaN(id) || !['approve', 'reject', 'spam'].includes(action)) {
    return new Response(null, { status: 303, headers: { Location: '/admin?error=invalid' } });
  }

  const statusMap: Record<string, 'approved' | 'rejected' | 'spam'> = {
    approve: 'approved',
    reject: 'rejected',
    spam: 'spam',
  };

  moderateEntry(id, statusMap[action], note, session.id);

  return new Response(null, { status: 303, headers: { Location: '/admin' } });
};
