import { Request, Response, NextFunction } from 'express';
import { UnauthorizedError } from '../lib/errors';
import { deviceAuth } from './deviceAuth';

/**
 * Before a large body is read (Sprint 7 hardening): a call must at least
 * carry a sign-in token or a device key. The route still checks them in full;
 * this only stops anonymous callers from making the server parse megabytes.
 */
export function credentialsFirst(req: Request, _res: Response, next: NextFunction): void {
  const bearer = /^Bearer\s+\S+/i.test(req.header('authorization') ?? '');
  const device = !!req.header('x-device-serial') && !!req.header('x-device-key');
  if (!bearer && !device) return next(new UnauthorizedError('Sign in first'));
  next();
}

/**
 * For a machine's feed path: the device key is checked in full before the
 * body is read — on that exact path only. Anything under it (a signed-in
 * screen's own route, e.g. readings/manual) just needs credentials present.
 */
export function deviceFirst(req: Request, res: Response, next: NextFunction): void {
  if (req.path === '/' || req.path === '') return deviceAuth(req, res, next);
  credentialsFirst(req, res, next);
}
