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

export async function requireTenant(req: Request, res: Response, next: NextFunction) {
  if (!req.companyId) {
    return res.status(401).json({
      error: 'unauthenticated',
      message: 'Tenant context missing — requireCompanyAuth must run first',
      statusCode: 401,
    })
  }

  const company = await prisma.company.findUnique({ where: { id: req.companyId } })
  if (!company) {
    return res.status(401).json({
      error: 'company_not_found',
      message: 'Company not found',
      statusCode: 401,
    })
  }

  req.company = company
  next()
}
