import { Request, Response, NextFunction } from 'express'
import jwt from 'jsonwebtoken'
import { prisma } from '../lib/prisma'
import { sendUnauthorized } from './authHelpers'

/**
 * 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 authHeader = req.headers.authorization
  const token = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : null

  if (!token) return sendUnauthorized(res, 'unauthenticated', 'Renter 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 token')
  }

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

  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
  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 authHeader = req.headers.authorization
  const token = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : null
  if (!token) return next()

  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET!) as { sub: string; type: string }
    if (payload.type === 'renter') req.renterId = payload.sub
  } catch {
    // Optional — silently ignore invalid tokens
  }

  next()
}
