import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret';

export interface AuthRequest extends Request {
  organizerId?: string;
}

export interface CheckpointAuthRequest extends Request {
  checkpointId?: string;
  eventId?: string;
}

export function requireAuth(
  req: AuthRequest,
  res: Response,
  next: NextFunction
): void {
  const header = req.headers.authorization;
  if (!header || !header.startsWith('Bearer ')) {
    res.status(401).json({ error: 'Missing or invalid authorization header' });
    return;
  }

  const token = header.slice(7);
  try {
    const payload = jwt.verify(token, JWT_SECRET) as { organizerId: string };
    req.organizerId = payload.organizerId;
    next();
  } catch {
    res.status(401).json({ error: 'Invalid or expired token' });
  }
}

export function requireCheckpointAuth(
  req: CheckpointAuthRequest,
  res: Response,
  next: NextFunction
): void {
  const header = req.headers.authorization;
  if (!header || !header.startsWith('Bearer ')) {
    res.status(401).json({ error: 'Missing or invalid authorization header' });
    return;
  }

  const token = header.slice(7);
  try {
    const payload = jwt.verify(token, JWT_SECRET) as {
      checkpointId: string;
      eventId: string;
    };
    req.checkpointId = payload.checkpointId;
    req.eventId = payload.eventId;
    next();
  } catch {
    res.status(401).json({ error: 'Invalid or expired checkpoint token' });
  }
}

export interface SuperAdminAuthRequest extends Request {
  superAdminEmail?: string;
}

export function requireSuperAdmin(
  req: SuperAdminAuthRequest,
  res: Response,
  next: NextFunction
): void {
  const header = req.headers.authorization;
  if (!header || !header.startsWith('Bearer ')) {
    res.status(401).json({ error: 'Missing or invalid authorization header' });
    return;
  }

  const token = header.slice(7);
  try {
    const payload = jwt.verify(token, JWT_SECRET) as { role?: string; email?: string };
    if (payload.role !== 'super_admin') {
      res.status(403).json({ error: 'Super admin access required' });
      return;
    }
    req.superAdminEmail = payload.email;
    next();
  } catch {
    res.status(401).json({ error: 'Invalid or expired super admin token' });
  }
}

