import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { Request } from 'express';

export interface JwtPayload {
  sub: string; // User-ID
  email: string;
  role: string;
  tenantId?: string;
  tenantSlug?: string;
  jti: string; // Token-ID fuer Revocation
  iat: number;
  exp: number;
}

/**
 * @CurrentUser() - Extrahiert den authentifizierten User aus dem Request.
 *
 * Beispiel:
 *   @Get('profile')
 *   getProfile(@CurrentUser() user: JwtPayload) {
 *     return user;
 *   }
 *
 *   @Get('profile/id')
 *   getProfileId(@CurrentUser('sub') userId: string) {
 *     return userId;
 *   }
 */
export const CurrentUser = createParamDecorator(
  (data: keyof JwtPayload | undefined, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest<Request>();
    const user = request.user as JwtPayload;
    return data ? user?.[data] : user;
  },
);
