import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { getSession, type AuthedUser } from '@bmm/auth';

const SESSION_COOKIE = 'bmm_session';

declare module 'fastify' {
  interface FastifyRequest {
    user?: AuthedUser;
  }
}

export async function requireAuth(
  req: FastifyRequest,
  reply: FastifyReply,
): Promise<FastifyReply | void> {
  const token = req.cookies[SESSION_COOKIE];
  const session = await getSession(token);
  if (!session) {
    return reply.code(401).send({ error: 'unauthorized' });
  }
  req.user = session;
}

export async function requireAdmin(
  req: FastifyRequest,
  reply: FastifyReply,
): Promise<FastifyReply | void> {
  const token = req.cookies[SESSION_COOKIE];
  const session = await getSession(token);
  if (!session) {
    return reply.code(401).send({ error: 'unauthorized' });
  }
  if (!session.isAdmin) {
    return reply.code(403).send({ error: 'forbidden' });
  }
  req.user = session;
}

export function registerSession(_app: FastifyInstance): void {
  // no-op; preHandler `requireAuth` does the work per-route
}
