import { Request, Response, NextFunction } from 'express'
import { verifyAccessToken } from '../lib/jwt'

export interface AuthRequest extends Request {
  user?: { id: string; orgId: string; role: string }
  orgId?: string
}

export function authMiddleware(req: AuthRequest, res: Response, next: NextFunction) {
  const authHeader = req.headers.authorization
  let token: string | undefined
  if (authHeader && authHeader.startsWith('Bearer ')) {
    token = authHeader.substring(7)
  } else if (typeof req.query.token === 'string') {
    token = req.query.token
  }
  if (!token) {
    return res.status(401).json({ success: false, error: { code: 'UNAUTHORIZED', message: '未提供认证令牌' } })
  }
  const payload = verifyAccessToken(token)
  if (!payload) {
    return res.status(401).json({ success: false, error: { code: 'TOKEN_INVALID', message: '令牌无效或已过期' } })
  }
  req.user = { id: payload.id, orgId: payload.orgId || '', role: payload.role }
  // 非 SUPER_ADMIN 用户必须有 orgId，否则企业端 API 会因 orgId=null 报错
  if (payload.role !== 'SUPER_ADMIN' && !payload.orgId) {
    return res.status(403).json({ success: false, error: { code: 'NO_ORG', message: '该账号未绑定企业' } })
  }
  next()
}

export function orgFilterMiddleware(req: AuthRequest, _res: Response, next: NextFunction) {
  if (req.user) {
    req.orgId = req.user.orgId
  }
  next()
}

/**
 * 平台管理员鉴权中间件，仅允许 SUPER_ADMIN 角色通过
 */
export function platformAdminMiddleware(req: AuthRequest, res: Response, next: NextFunction) {
  if (!req.user || req.user.role !== 'SUPER_ADMIN') {
    return res.status(403).json({ success: false, error: { code: 'FORBIDDEN', message: '需要平台管理员权限' } })
  }
  next()
}
