import type { Handle } from '@sveltejs/kit';
import { redirect } from '@sveltejs/kit';
import { getSessionUser, seedDefaultAdminIfMissing } from '$lib/server/auth';

const seed = seedDefaultAdminIfMissing();
if (seed.tempPassword) {
  console.log(
    `[admin] seeded default admin: username="${seed.username}" password="${seed.tempPassword}" (change it from /admin)`
  );
}

export const handle: Handle = async ({ event, resolve }) => {
  event.locals.admin = getSessionUser(event.cookies);

  const p = event.url.pathname;
  const isAdminArea = p === '/admin' || p.startsWith('/admin/');
  const isLogin = p === '/admin/login';

  if (isAdminArea && !isLogin && !event.locals.admin) {
    throw redirect(303, '/admin/login');
  }
  if (isLogin && event.locals.admin) {
    throw redirect(303, '/admin');
  }

  return resolve(event);
};
