import type { APIRoute } from 'astro';
import { timingSafeEqual } from 'node:crypto';
import { createSession, SESSION_COOKIE, sessionCookieOptions } from '../../../lib/auth';

export const prerender = false;

function tokenMatches(input: string, expected: string): boolean {
  const a = Buffer.from(input);
  const b = Buffer.from(expected);
  if (a.length !== b.length) return false;
  return timingSafeEqual(a, b);
}

export const POST: APIRoute = async ({ request, cookies }) => {
  const expectedToken = process.env.ADMIN_SECRET_TOKEN?.trim();
  if (!expectedToken) {
    return new Response(null, { status: 404 });
  }

  const formData = await request.formData();
  const token = String(formData.get('token') ?? '').trim();

  if (!tokenMatches(token, expectedToken)) {
    return new Response(null, {
      status: 303,
      headers: { Location: '/admin/login?tokenError=1' },
    });
  }

  const sessionId = createSession('admin');
  cookies.set(SESSION_COOKIE, sessionId, sessionCookieOptions(24 * 60 * 60));

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