import { NextApiRequest, NextApiResponse } from 'next'
import { verifyAccessToken } from '@/lib/utils/jwt'
import { authService } from '@/lib/services/auth'
import { UserRole } from '@/types/auth'

export interface AuthenticatedRequest extends NextApiRequest {
  user: {
    id: string
    email: string
    role: UserRole
    name: string | null
  }
}

export function withAuth(
  handler: (req: AuthenticatedRequest, res: NextApiResponse) => Promise<void>
) {
  return async (req: NextApiRequest, res: NextApiResponse) => {
    try {
      // 获取令牌
      const authHeader = req.headers.authorization
      if (!authHeader) {
        return res.status(401).json({
          success: false,
          error: '未提供认证令牌'
        })
      }

      const token = authHeader.replace('Bearer ', '')
      if (!token) {
        return res.status(401).json({
          success: false,
          error: '认证令牌格式错误'
        })
      }

      // 验证令牌
      const decoded = verifyAccessToken(token)

      // 获取用户信息
      const user = await authService.getUserById(decoded.userId)
      if (!user) {
        return res.status(401).json({
          success: false,
          error: '用户不存在'
        })
      }

      // 检查用户状态
      if (user.status !== 'ACTIVE') {
        return res.status(401).json({
          success: false,
          error: '用户账户状态异常'
        })
      }

      // 将用户信息附加到请求对象
      ;(req as AuthenticatedRequest).user = {
        id: user.id,
        email: user.email,
        role: user.role as UserRole,
        name: user.name
      }

      return handler(req as AuthenticatedRequest, res)

    } catch (error: any) {
      return res.status(401).json({
        success: false,
        error: error.message || '认证失败'
      })
    }
  }
}

export function withRole(allowedRoles: UserRole[]) {
  return function(
    handler: (req: AuthenticatedRequest, res: NextApiResponse) => Promise<void>
  ) {
    return withAuth(async (req: AuthenticatedRequest, res: NextApiResponse) => {
      // 检查用户角色
      if (!allowedRoles.includes(req.user.role)) {
        return res.status(403).json({
          success: false,
          error: '权限不足'
        })
      }

      return handler(req, res)
    })
  }
}

export function withAdminRole(
  handler: (req: AuthenticatedRequest, res: NextApiResponse) => Promise<void>
) {
  return withRole([UserRole.ADMIN])(handler)
}

export function withModeratorRole(
  handler: (req: AuthenticatedRequest, res: NextApiResponse) => Promise<void>
) {
  return withRole([UserRole.ADMIN, UserRole.MODERATOR])(handler)
}

// 中间件工厂函数，用于组合多个中间件
export function compose(...middlewares: Function[]) {
  return (handler: Function) => {
    return middlewares.reduce((acc, middleware) => {
      return middleware(acc)
    }, handler)
  }
}

// 错误处理中间件
export function withErrorHandler(
  handler: (req: NextApiRequest, res: NextApiResponse) => Promise<void>
) {
  return async (req: NextApiRequest, res: NextApiResponse) => {
    try {
      await handler(req, res)
    } catch (error: any) {
      console.error('API Error:', error)
      
      if (res.headersSent) {
        return
      }

      res.status(500).json({
        success: false,
        error: process.env.NODE_ENV === 'development' 
          ? error.message 
          : '服务器内部错误'
      })
    }
  }
}

// 请求日志中间件
export function withRequestLogging(
  handler: (req: NextApiRequest, res: NextApiResponse) => Promise<void>
) {
  return async (req: NextApiRequest, res: NextApiResponse) => {
    const start = Date.now()
    const { method, url } = req
    
    console.log(`${method} ${url} - Start`)

    try {
      await handler(req, res)
    } finally {
      const duration = Date.now() - start
      console.log(`${method} ${url} - ${res.statusCode} (${duration}ms)`)
    }
  }
}