import type { ExecutionContext } from "@nestjs/common";
import { createParamDecorator, UnauthorizedException } from "@nestjs/common";
import type { AuthUser } from "@mosaic/shared";
import type { MaybeAuthenticatedRequest } from "../types/better-auth-request.interface";

export const CurrentUser = createParamDecorator(
  (_data: unknown, ctx: ExecutionContext): AuthUser => {
    // Use MaybeAuthenticatedRequest because the decorator doesn't know
    // whether AuthGuard ran — the null check provides defense-in-depth.
    const request = ctx.switchToHttp().getRequest<MaybeAuthenticatedRequest>();
    if (!request.user) {
      throw new UnauthorizedException("No authenticated user found on request");
    }
    return request.user;
  }
);
