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

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 res.status(401).json({ error: 'unauthenticated', message: 'Renter authentication required', statusCode: 401 })
  }

  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET!) as { sub: string; type: string }
    if (payload.type !== 'renter') {
      return res.status(401).json({ error: 'invalid_token', message: 'Invalid token type', statusCode: 401 })
    }

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

    req.renterId = renter.id
    next()
  } catch {
    return res.status(401).json({ error: 'invalid_token', message: 'Invalid or expired token', statusCode: 401 })
  }
}

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 — ignore invalid tokens
  }

  next()
}
