export const prerender = false;

import type { APIRoute } from 'astro';
import { ADMIN_COOKIE, createSession, verifyPassword } from '../../../lib/auth';

export const POST: APIRoute = async ({ request, cookies }) => {
  let body: { password?: string } = {};
  try {
    body = await request.json();
  } catch {
    return new Response(JSON.stringify({ error: 'invalid_body' }), { status: 400 });
  }

  const password = body.password ?? '';
  const valid = await verifyPassword(password);
  if (!valid) {
    return new Response(JSON.stringify({ error: 'invalid_credentials' }), {
      status: 401,
      headers: { 'Content-Type': 'application/json' },
    });
  }

  const token = await createSession();
  cookies.set(ADMIN_COOKIE, token, {
    httpOnly: true,
    secure: import.meta.env.PROD,
    sameSite: 'strict',
    path: '/',
    maxAge: 60 * 60 * 24 * 7,
  });

  return new Response(JSON.stringify({ ok: true }), {
    headers: { 'Content-Type': 'application/json' },
  });
};
