import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { Request } from 'express';
import { API_KEY_HEADER, DEPARTMENT_CODE_HEADER, ERROR_CODES } from '../constants';

@Injectable()
export class ApiKeyGuard implements CanActivate {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest<Request>();
    const apiKey = request.headers[API_KEY_HEADER] as string;
    const departmentCode = request.headers[DEPARTMENT_CODE_HEADER] as string;

    if (!apiKey) {
      throw new UnauthorizedException({
        code: ERROR_CODES.INVALID_API_KEY,
        message: 'API key is required',
      });
    }

    if (!departmentCode) {
      throw new UnauthorizedException({
        code: ERROR_CODES.INVALID_API_KEY,
        message: 'Department code is required',
      });
    }

    // Note: Actual validation is done in AuthService
    // This guard just ensures the headers are present
    // The AuthModule middleware validates the API key

    return true;
  }
}
