/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import {
  Injectable,
  CanActivate,
  ExecutionContext,
  HttpException,
  HttpStatus,
} from '@nestjs/common';

@Injectable()
export class SelfGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    const requestedId = request.params.id;

    if (!user) {
      throw new HttpException(
        'Credenciales inválidas',
        HttpStatus.UNAUTHORIZED,
      );
    }

    if (!requestedId) {
      throw new HttpException(
        'No se proporcionó credencial',
        HttpStatus.FORBIDDEN,
      );
    }

    if (user.userId !== requestedId) {
      throw new HttpException(
        'No se proporcionó credencial',
        HttpStatus.FORBIDDEN,
      );
    }

    return true;
  }
}
