import type { APIContext } from 'astro';

const sessionCookie = 'ruseemrooz_admin';

const getAdminUser = () => import.meta.env.ADMIN_USER ?? 'admin';
const getAdminPassword = () => import.meta.env.ADMIN_PASSWORD ?? 'admin123';
const getSessionSecret = () => import.meta.env.ADMIN_SESSION_SECRET ?? 'local-session';

const encodeToken = () => Buffer.from(`${getAdminUser()}:${getSessionSecret()}`).toString('base64url');

export const isValidLogin = (username: string, password: string) => (
  username === getAdminUser() && password === getAdminPassword()
);

export const setAdminSession = (context: APIContext) => {
  context.cookies.set(sessionCookie, encodeToken(), {
    path: '/',
    httpOnly: true,
    sameSite: 'lax',
    secure: import.meta.env.PROD,
    maxAge: 60 * 60 * 8,
  });
};

export const clearAdminSession = (context: APIContext) => {
  context.cookies.delete(sessionCookie, { path: '/' });
};

export const isAdminAuthenticated = (context: APIContext) => (
  context.cookies.get(sessionCookie)?.value === encodeToken()
);

export const requireAdmin = (context: APIContext) => {
  if (!isAdminAuthenticated(context)) {
    return new Response('Unauthorized', { status: 401 });
  }

  return null;
};
