import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnprocessableEntityException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class SetupSchedulingGuard implements CanActivate {
  constructor(private readonly jwtService: JwtService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const jwtAuth = request.headers['authorization'];
    const setupAuth = request.headers['x-setup-authorization'];

    if (setupAuth) {
      try {
        const setupKey = process.env.SETUP_SCHEDULING_KEY;
        if (setupAuth === setupKey) return true;
        else new UnprocessableEntityException('Setup Authorization Not Found.');
      } catch (err) {
        throw new UnprocessableEntityException('Invalid authentication.');
      }
    } else if (jwtAuth && jwtAuth.startsWith('Bearer ')) {
      const token = jwtAuth.split(' ')[1];
      try {
        const payload = await this.jwtService.verifyAsync(token);
        if (payload) return true;
        else new UnprocessableEntityException('Setup Authorization Not Found.');
        return true;
      } catch (err) {
        throw new UnprocessableEntityException('Invalid JWT token');
      }
    }

    throw new UnprocessableEntityException('Invalid authentication');
  }
}
