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

export interface CurrentUserData {
  id: string;
  email: string;
  tenantId: string;
  role: string;
}

/**
 * Decorator para obtener el usuario actual del request.
 *
 * @example
 * @Get('me')
 * async getProfile(@CurrentUser() user: CurrentUserData) {
 *   return this.userService.findById(user.id);
 * }
 *
 * // Obtener solo una propiedad
 * @Get('tenant')
 * async getTenant(@CurrentUser('tenantId') tenantId: string) {
 *   return this.tenantService.findById(tenantId);
 * }
 */
export const CurrentUser = createParamDecorator(
  (data: keyof CurrentUserData | undefined, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    const user = request.user as CurrentUserData;

    if (!user) {
      return null;
    }

    return data ? user[data] : user;
  },
);
