import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Roles } from '../role.decorator';
import { AuthAdminService } from './authAdmin.service';
import { AdminService } from 'src/admin/admin.service';

@Injectable()
export class AuthAdminGuard implements CanActivate {
  constructor(
    private authAdminService: AuthAdminService,
    private adminService: AdminService,
    private reflector: Reflector,
  ) {}
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const requiredRole = this.reflector.get(Roles, context.getHandler());
    if (!requiredRole) return true;
    const request = context.switchToHttp().getRequest();
    let { authorization }: any = request.headers;
    if (!authorization) throw new UnauthorizedException('session expired! Please sign In');
    authorization = authorization.split(' ')[1];
    const jwtPayload = await this.authAdminService.validateToken(authorization);
    if (!requiredRole.includes(jwtPayload.role)) throw new UnauthorizedException('Unauthorized access');
    const admin = await this.adminService.findOne(jwtPayload.email);
    request.admin = { ...admin };
    return true;
  }
}
