import { redirect } from '@sveltejs/kit';
import { getDb } from '$lib/server/db.js';
import { startBackupScheduler } from '$lib/server/backup.js';
import {
  isAdminAuthed,
  isAdminPath,
  isLoginPath,
  refreshAdminCookie
} from '$lib/server/admin-auth.js';

// Open (and warm) the database on server startup so the first request
// doesn't pay the cost.
getDb();
startBackupScheduler();

/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
  const path = event.url.pathname;
  if (isAdminPath(path) && !isLoginPath(path)) {
    if (!isAdminAuthed(event)) {
      const next = path + event.url.search;
      throw redirect(303, `/admin/login?next=${encodeURIComponent(next)}`);
    }
    // Sliding 5-minute expiry: any request under /admin extends the session.
    refreshAdminCookie(event);
  }
  return resolve(event);
}
