import path from 'path';
import { Request, Response, NextFunction } from 'express';

const ALLOWED_MIME_TYPES = new Set([
  'video/mp4',
  'video/quicktime',
  'video/x-matroska',
  'video/webm',
  'video/avi',
]);

export function pathTraversalGuard(allowedBase: string) {
  return (req: Request, res: Response, next: NextFunction): void => {
    const id = req.params.videoId || req.params.id || '';
    if (!id) { next(); return; }
    const resolved = path.resolve(allowedBase, id);
    if (!resolved.startsWith(path.resolve(allowedBase))) {
      res.status(400).json({ error: 'Invalid path' });
      return;
    }
    next();
  };
}

export function validateMimeType(mimeType: string): boolean {
  return ALLOWED_MIME_TYPES.has(mimeType);
}

export function securityHeaders(_req: Request, res: Response, next: NextFunction): void {
  res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
  res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp');
  next();
}
