import { Request, Response, NextFunction } from 'express';
import { User } from '@shared/schema';

// Extend Express Request to include user session data
declare module 'express-serve-static-core' {
  interface Request {
    user?: User;
  }
}

// Extend session data to include user info
declare module 'express-session' {
  interface SessionData {
    userId?: string;
    user?: {
      id: string;
      name: string;
      email: string;
      role: 'client' | 'pharmacy' | 'courier' | 'admin';
      phone: string;
    };
  }
}

// Middleware to check if user is authenticated
export const requireAuth = (req: Request, res: Response, next: NextFunction) => {
  if (!req.session?.userId || !req.session?.user) {
    return res.status(401).json({ 
      message: 'Non authentifié', 
      redirect: '/login' 
    });
  }
  
  // Attach user to request object for easy access
  req.user = req.session.user as User;
  next();
};

// Middleware to check if user has specific role(s)
export const requireRole = (...allowedRoles: string[]) => {
  return (req: Request, res: Response, next: NextFunction) => {
    if (!req.session?.user) {
      return res.status(401).json({ 
        message: 'Non authentifié',
        redirect: '/login' 
      });
    }

    if (!allowedRoles.includes(req.session.user.role)) {
      return res.status(403).json({ 
        message: 'Accès non autorisé pour votre rôle' 
      });
    }

    req.user = req.session.user as User;
    next();
  };
};

// Middleware to get user info if authenticated (optional auth)
export const optionalAuth = (req: Request, res: Response, next: NextFunction) => {
  if (req.session?.userId && req.session?.user) {
    req.user = req.session.user as User;
  }
  next();
};

// Helper function to create user session
export const createUserSession = (req: Request, user: User): void => {
  req.session.userId = user.id;
  req.session.user = {
    id: user.id,
    name: user.name,
    email: user.email || '',
    role: user.role,
    phone: user.phone
  };
};

// Helper function to destroy user session
export const destroyUserSession = (req: Request): Promise<void> => {
  return new Promise((resolve, reject) => {
    req.session.destroy((err) => {
      if (err) reject(err);
      else resolve();
    });
  });
};

// Middleware to check if user is already authenticated (for login/register pages)
export const requireGuest = (req: Request, res: Response, next: NextFunction) => {
  if (req.session?.userId) {
    return res.status(302).json({ 
      message: 'Déjà connecté',
      redirect: '/dashboard' 
    });
  }
  next();
};