import { Injectable } from "@nestjs/common";
import type { ClientRequest } from "node:http";
import type { AiProvider } from "./provider.interface";

@Injectable()
export class AnthropicProvider implements AiProvider {
  readonly name = "anthropic";
  readonly baseUrl: string;
  private readonly upstreamApiKey: string;

  constructor() {
    const baseUrl = process.env.UPSTREAM_BASE_URL ?? "https://api.anthropic.com";
    const apiKey = process.env.UPSTREAM_API_KEY ?? "";
    if (!apiKey) {
      throw new Error("UPSTREAM_API_KEY is required");
    }
    this.baseUrl = baseUrl.replace(/\/+$/, "");
    this.upstreamApiKey = apiKey;
  }

  applyToProxyReq(proxyReq: ClientRequest): void {
    proxyReq.removeHeader("authorization");
    proxyReq.removeHeader("x-gateway-token");
    proxyReq.setHeader("x-api-key", this.upstreamApiKey);
    if (!proxyReq.getHeader("anthropic-version")) {
      proxyReq.setHeader("anthropic-version", "2023-06-01");
    }
  }
}
