import { Request, Response, NextFunction } from 'express';
import { ConfigSingleton } from '../config/ConfigSingleton';
import { UnauthorizedError } from '../types/errors';

export function attendanceApiKey(req: Request, _res: Response, next: NextFunction): void {
  const key = req.headers['x-attendance-api-key'];
  if (key !== ConfigSingleton.getInstance().attendanceApiKey) {
    next(new UnauthorizedError('Invalid attendance API key'));
    return;
  }
  next();
}

export function calendarApiKeyOrBearer(
  req: Request,
  _res: Response,
  next: NextFunction,
): void {
  const apiKey = req.headers['x-api-key'];
  if (apiKey === ConfigSingleton.getInstance().calendarApiKey) {
    next();
    return;
  }
  const header = req.headers.authorization;
  if (header?.startsWith('Bearer ')) {
    try {
      const { AuthTokenRepository } = require('../repositories/AuthTokenRepository');
      const repo = new AuthTokenRepository();
      const payload = repo.verifyEmployeeJwt(header.slice(7));
      req.employeeId = payload.employeeId;
      next();
      return;
    } catch {
      /* fall through */
    }
  }
  next(new UnauthorizedError('Calendar API authentication required'));
}
