import {
  createParamDecorator,
  ExecutionContext,
  SetMetadata,
} from '@nestjs/common';
import type { FastifyRequest } from 'fastify';

import type { AuthenticatedUser, SessionContext } from '@hexahost/auth';

export const IS_PUBLIC_KEY = 'isPublic';

export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);

export interface RequestWithSession extends FastifyRequest {
  session?: SessionContext;
  user?: AuthenticatedUser;
}

export const CurrentUser = createParamDecorator(
  (_data: unknown, context: ExecutionContext): AuthenticatedUser => {
    const request = context.switchToHttp().getRequest<RequestWithSession>();
    if (!request.user) {
      throw new Error('CurrentUser decorator requires SessionGuard');
    }
    return request.user;
  },
);

export const CurrentSession = createParamDecorator(
  (_data: unknown, context: ExecutionContext): SessionContext => {
    const request = context.switchToHttp().getRequest<RequestWithSession>();
    if (!request.session) {
      throw new Error('CurrentSession decorator requires SessionGuard');
    }
    return request.session;
  },
);
