import { Request, Response, NextFunction } from 'express';

export function bodyOtp(req: Request): string | undefined {
  return (req.body?.md_otp as string) || (req.headers['x-md-otp'] as string);
}

export function verifyMdOtp(req: Request, res: Response, next: NextFunction): void {
  const expected = process.env.MD_OTP;
  if (!expected) {
    res.status(500).json({ success: false, error: 'MD_OTP not configured' });
    return;
  }
  const got = bodyOtp(req);
  if (!got || got !== expected) {
    res.status(403).json({ success: false, error: 'Invalid or missing MD OTP' });
    return;
  }
  next();
}
