import {
  Injectable,
  ExecutionContext,
  ForbiddenException,
} from '@nestjs/common';
import { JWTGuard } from './jwt.guard';
import { MAIN_MENU } from '../constants';

@Injectable()
export class RolesGuard extends JWTGuard {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    await super.canActivate(context);

    // jika endpoint tersebut bukan public, maka lakukan check lanjutan
    if (!this.isPublic) {
      // Check apakah endpoint ada decorator untuk exlude privilege (@ExcludePrivilege())
      const excludePrivilege = this.reflector.getAllAndOverride<boolean>(
        MAIN_MENU,
        [context.getHandler(), context.getClass()],
      );
      if (excludePrivilege) return true;

      // check apakah dapat akses module
      const isNotAllow = await this.privilege.isNotAllowed();
      if (isNotAllow) {
        throw new ForbiddenException({
          statusCode: 10003,
          message: `Akses Terlarang, anda tidak punya akses ke module ini!`,
          error: 'ACCESS_FORBIDDEN',
        });
      }
    }

    return true;
  }
}
