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

const authRepo = new AuthTokenRepository();

export function employeeAuth(req: Request, _res: Response, next: NextFunction): void {
  try {
    const header = req.headers.authorization;
    if (!header?.startsWith('Bearer ')) throw new UnauthorizedError();
    const payload = authRepo.verifyEmployeeJwt(header.slice(7));
    req.employeeId = payload.employeeId;
    next();
  } catch (e) {
    next(e instanceof UnauthorizedError ? e : new UnauthorizedError());
  }
}
