import { Request, Response, NextFunction } from 'express'
import { prisma } from '../../lib/prisma'
import { getAccessLevel, hasAnyAccess } from './subscription.policy'

export async function requireActiveSubscription(req: Request, res: Response, next: NextFunction) {
  const companyId = req.companyId
  if (!companyId) return res.status(401).json({ error: 'unauthenticated' })

  const sub = await prisma.subscription.findUnique({ where: { companyId } })
  const status = sub?.status ?? 'EXPIRED'
  const accessLevel = getAccessLevel(status)

  if (!hasAnyAccess(status)) {
    return res.status(403).json({
      error: 'subscription_required',
      message: 'Your subscription has ended. Please reactivate to continue.',
      subscriptionStatus: status,
      accessLevel,
    })
  }

  ;(req as any).subscriptionStatus = status
  ;(req as any).accessLevel = accessLevel
  next()
}

export async function requireFullAccess(req: Request, res: Response, next: NextFunction) {
  const companyId = req.companyId
  if (!companyId) return res.status(401).json({ error: 'unauthenticated' })

  const sub = await prisma.subscription.findUnique({ where: { companyId } })
  const status = sub?.status ?? 'EXPIRED'
  const accessLevel = getAccessLevel(status)

  if (accessLevel !== 'full') {
    return res.status(403).json({
      error: 'insufficient_access',
      message: 'This action requires an active subscription.',
      subscriptionStatus: status,
      accessLevel,
    })
  }

  ;(req as any).subscriptionStatus = status
  ;(req as any).accessLevel = accessLevel
  next()
}
