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

export async function requireApiKey(req: Request, res: Response, next: NextFunction) {
  const apiKey = req.headers['x-api-key'] as string | undefined

  if (!apiKey) {
    return res.status(401).json({ error: 'missing_api_key', message: 'API key required in x-api-key header', statusCode: 401 })
  }

  const company = await prisma.company.findUnique({ where: { apiKey } })
  if (!company) {
    return res.status(401).json({ error: 'invalid_api_key', message: 'Invalid API key', statusCode: 401 })
  }

  req.company = company
  req.companyId = company.id
  next()
}
