import { fail, redirect } from '@sveltejs/kit';
import {
  ADMIN_PASSWORD,
  isAdminAuthed,
  refreshAdminCookie
} from '$lib/server/admin-auth.js';

function safeNext(raw) {
  if (!raw) return '/admin';
  if (!raw.startsWith('/admin')) return '/admin';
  if (raw === '/admin/login' || raw.startsWith('/admin/login/')) return '/admin';
  return raw;
}

export function load(event) {
  if (isAdminAuthed(event)) {
    throw redirect(303, safeNext(event.url.searchParams.get('next')));
  }
  return {};
}

export const actions = {
  default: async (event) => {
    const data = await event.request.formData();
    const password = String(data.get('password') ?? '');
    if (password !== ADMIN_PASSWORD) {
      return fail(401, { error: 'admin.login.wrong_password' });
    }
    refreshAdminCookie(event);
    throw redirect(303, safeNext(event.url.searchParams.get('next')));
  }
};
