import {
  CanActivate,
  ExecutionContext,
  HttpStatus,
  Injectable,
} from '@nestjs/common';
import { createGeneralError } from '../../utils';
import { RecruitmentService } from './recruitment.service';

@Injectable()
export class ApiKeyGuard implements CanActivate {
  constructor(private readonly recruitmentService: RecruitmentService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const ownerId = request.headers['x-tenant-id'];
    const apiKey = request.headers['x-api-key'];

    if (!ownerId || !apiKey) {
      throw createGeneralError(
        'Missing API credentials',
        'authorization',
        HttpStatus.UNAUTHORIZED,
      );
    }

    const record = await this.recruitmentService.validateApiKey(
      String(ownerId),
      String(apiKey),
    );

    if (!record) {
      throw createGeneralError(
        'Invalid API key',
        'authorization',
        HttpStatus.UNAUTHORIZED,
      );
    }

    request.tenantOwnerId = record.owner_id;
    return true;
  }
}
