import { Request, Response, NextFunction } from 'express'
import jwt from 'jsonwebtoken'
import { prisma } from '../lib/prisma'
import { AdminRole } from '@rentaldrivego/database'
import { sendUnauthorized, sendForbidden } from './authHelpers'

const ROLE_RANK: Record<AdminRole, number> = {
  SUPER_ADMIN: 5,
  ADMIN:       4,
  SUPPORT:     3,
  FINANCE:     2,
  VIEWER:      1,
}

/**
 * Requires a valid admin Bearer token.
 *
 * Guarantees on success:
 *   req.admin — the full AdminUser record
 */
export async function requireAdminAuth(req: Request, res: Response, next: NextFunction) {
  const authHeader = req.headers.authorization
  const token = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : null

  if (!token) return sendUnauthorized(res, 'unauthenticated', 'Admin authentication required')

  let payload: { sub: string; type: string }
  try {
    payload = jwt.verify(token, process.env.JWT_SECRET!) as { sub: string; type: string }
  } catch {
    return sendUnauthorized(res, 'invalid_token', 'Invalid or expired admin token')
  }

  if (payload.type !== 'admin') {
    return sendUnauthorized(res, 'invalid_token', 'Invalid token type')
  }

  const admin = await prisma.adminUser.findUnique({ where: { id: payload.sub } })
  if (!admin || !admin.isActive) {
    return sendUnauthorized(res, 'unauthenticated', 'Admin account not found or deactivated')
  }

  req.admin = admin
  next()
}

/**
 * Requires the authenticated admin to have at least `minimumRole`.
 * Must be applied after `requireAdminAuth`.
 */
export function requireAdminRole(minimumRole: AdminRole) {
  return (req: Request, res: Response, next: NextFunction) => {
    const admin = req.admin
    if (!admin) return sendUnauthorized(res, 'unauthenticated', 'Admin authentication required')

    const rank     = ROLE_RANK[admin.role]   ?? 0
    const required = ROLE_RANK[minimumRole]  ?? 99

    if (rank < required) {
      return sendForbidden(res, 'forbidden', `This action requires the ${minimumRole} role or higher`)
    }

    next()
  }
}
