import type { SportsDataProvider, ProviderEvent, ProviderSport } from "@/server/providers/odds/types";

export class HttpOddsProvider implements SportsDataProvider {
  constructor(
    private readonly baseUrl: string,
    private readonly apiKey: string
  ) {}

  async listSports(): Promise<ProviderSport[]> {
    return this.request("/sports");
  }

  async listEvents(input?: { liveOnly?: boolean; sportSlug?: string }): Promise<ProviderEvent[]> {
    if (input?.liveOnly) return [];

    const params = new URLSearchParams();
    if (input?.sportSlug) params.set("sport", input.sportSlug);
    return this.request(`/events?${params.toString()}`);
  }

  async healthCheck() {
    const started = Date.now();
    await this.request("/health");
    return { ok: true, latencyMs: Date.now() - started };
  }

  private async request<T>(path: string): Promise<T> {
    const response = await fetch(new URL(path, this.baseUrl), {
      headers: {
        authorization: `Bearer ${this.apiKey}`,
        accept: "application/json"
      },
      cache: "no-store"
    });

    if (!response.ok) {
      throw new Error(`Odds provider request failed: ${response.status}`);
    }

    return response.json() as Promise<T>;
  }
}
