import { Request, Response, NextFunction } from 'express'
import jwt from 'jsonwebtoken'
import { User, UserRole } from '@skillmate/shared'

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production'

export interface AuthRequest extends Request {
  user?: User
}

export function authenticateToken(req: AuthRequest, res: Response, next: NextFunction) {
  const token = req.headers.authorization?.split(' ')[1]

  if (!token) {
    return res.status(401).json({ 
      success: false, 
      error: { message: 'No token provided' } 
    })
  }

  try {
    const decoded = jwt.verify(token, JWT_SECRET) as any
    req.user = decoded.user
    next()
  } catch (error) {
    return res.status(401).json({ 
      success: false, 
      error: { message: 'Invalid token' } 
    })
  }
}

export const authenticate = authenticateToken;

export function authorize(...roles: UserRole[]) {
  return (req: AuthRequest, res: Response, next: NextFunction) => {
    if (!req.user) {
      return res.status(401).json({ 
        success: false, 
        error: { message: 'Not authenticated' } 
      })
    }

    if (!roles.includes(req.user.role)) {
      return res.status(403).json({ 
        success: false, 
        error: { message: 'Insufficient permissions' } 
      })
    }

    next()
  }
}