import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-jwt';
import { Request } from 'express';
import { AuthService } from '../auth.service';
import { API_KEY_HEADER, DEPARTMENT_CODE_HEADER } from '../../../common/constants';

@Injectable()
export class ApiKeyStrategy extends PassportStrategy(Strategy, 'api-key') {
  constructor(private readonly authService: AuthService) {
    super({
      jwtFromRequest: (req: Request) => {
        const apiKey = req.headers[API_KEY_HEADER] as string;
        const departmentCode = req.headers[DEPARTMENT_CODE_HEADER] as string;

        if (!apiKey || !departmentCode) {
          return null;
        }

        // Return a dummy token - actual validation happens in validate()
        return `${apiKey}:${departmentCode}`;
      },
      secretOrKey: 'api-key-strategy',
    });
  }

  async validate(token: string): Promise<{ departmentId: string; departmentCode: string }> {
    const [apiKey, departmentCode] = token.split(':');

    if (!apiKey || !departmentCode) {
      throw new UnauthorizedException('API key and department code are required');
    }

    const result = await this.authService.validateDepartmentApiKey(apiKey, departmentCode);

    return {
      departmentId: result.department.id,
      departmentCode: result.department.code,
    };
  }
}
