import { Request, Response, NextFunction } from 'express'
import { prisma } from '../lib/prisma'
import { getAuthToken, sendUnauthorized } from './authHelpers'
import { verifyActorToken } from '../security/tokens'
import { getSessionCookieName } from '../security/sessionCookies'
import { actorLimiter } from './rateLimiter'

/**
 * Requires a valid renter Bearer token.
 *
 * Guarantees on success:
 *   req.renterId — the authenticated renter's id
 */
export async function requireRenterAuth(req: Request, res: Response, next: NextFunction) {
  const token = getAuthToken(req, getSessionCookieName('renter'))

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

  let payload: { sub: string; type: string }
  try {
    payload = verifyActorToken(token, 'renter')
  } catch {
    return sendUnauthorized(res, 'invalid_token', 'Invalid or expired token')
  }

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

  req.renterId = renter.id
  return actorLimiter(req, res, next)
}

/**
 * Optionally extracts renter identity from a Bearer token.
 * Never blocks the request — invalid or absent tokens are silently ignored.
 *
 * Sets on success:
 *   req.renterId — the authenticated renter's id (if token is valid)
 */
export async function optionalRenterAuth(req: Request, _res: Response, next: NextFunction) {
  const token = getAuthToken(req, getSessionCookieName('renter'))
  if (!token) return next()

  try {
    const payload = verifyActorToken(token, 'renter')
    req.renterId = payload.sub
  } catch {
    // Optional — silently ignore invalid tokens
  }

  next()
}
