import type { MiddlewareHandler } from 'hono';
import { getCookie, setCookie } from 'hono/cookie';
import type { Env } from '../env';
import { getSessionUser } from '../services/auth';
import { randomToken } from '../utils/id';

export const CSRF_COOKIE = 'wm_csrf';

export function sessionCookieName(env: Env['Bindings']): string {
  return env.COOKIE_NAME || 'wm_session';
}

export function getSessionToken(c: Parameters<MiddlewareHandler<Env>>[0]): string {
  return getCookie(c, sessionCookieName(c.env)) || '';
}

export function ensureCsrfToken(c: Parameters<MiddlewareHandler<Env>>[0]): string {
  let token = getCookie(c, CSRF_COOKIE);
  if (!token) {
    token = randomToken(24);
    setCookie(c, CSRF_COOKIE, token, {
      path: '/',
      httpOnly: false,
      sameSite: 'Lax',
      secure: new URL(c.req.url).protocol === 'https:'
    });
  }
  c.set('csrfToken', token);
  return token;
}

export const sessionMiddleware: MiddlewareHandler<Env> = async (c, next) => {
  const token = getSessionToken(c);
  const user = token ? await getSessionUser(c.env, token) : null;
  c.set('currentUser', user?.status === 'active' ? user : null);
  ensureCsrfToken(c);
  await next();
};
