import { posthog } from "../analytics"
import { userForAPIKey } from "@codeflash-ai/common/token-functions"

// Middleware to check for valid API key
export async function checkForValidAPIKey(req: AuthorizedUserReq, res, next: () => void) {
  const authHeader = req.headers.authorization
  if (authHeader == null) {
    posthog.capture({
      distinctId: "null-user-with-missing-authorization-header",
      event: `cfapi-endpoint-called-with-missing-authorization-header`,
      properties: {
        url: req.url,
        headers: req.headers,
        body: req.body,
      },
      disableGeoip: false,
    })
    return res.status(401).send("Authorization header is missing")
  }

  const apiKey = authHeader.replace(/^Bearer\s+/, "")
  const userId = await userForAPIKey(apiKey)
  if (userId == null) {
    console.log(`Userid null for API key ${apiKey}. Returning 403`)
    posthog.capture({
      distinctId: "null-user-with-invalid-api-key",
      event: `cfapi-endpoint-called-with-invalid-api-key`,
      properties: {
        apiKey,
      },
      disableGeoip: false,
    })
    return res.status(403).send("Invalid API key")
  }
  req.userId = userId

  next()
}
