import type { ApiEnvelope, PriceSeriesResponse } from "@/lib/api/types";

const SERVER_API_BASE =
  process.env.NEXT_PUBLIC_API_BASE_URL ??
  process.env.API_BASE_URL ??
  "http://127.0.0.1:8000";

export async function getInitialPriceSeries(
  asset = "BTC",
  timeframe = "15m",
  maxPoints = 240,
  timeoutMs = 1500,
): Promise<PriceSeriesResponse | null> {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeoutMs);
  const url = new URL("/api/v1/prices/series", SERVER_API_BASE);
  url.searchParams.set("asset", asset);
  url.searchParams.set("venue_scope", "all");
  url.searchParams.set("timeframe", timeframe);
  url.searchParams.set("max_points", String(maxPoints));

  const now = new Date();
  const start = new Date(now);
  start.setUTCDate(start.getUTCDate() - 1);
  url.searchParams.set("start", start.toISOString());

  try {
    const response = await fetch(url.toString(), {
      cache: "no-store",
      signal: controller.signal,
    });
    if (!response.ok) {
      return null;
    }
    const payload = (await response.json()) as ApiEnvelope<PriceSeriesResponse>;
    return payload.data ?? null;
  } catch {
    return null;
  } finally {
    clearTimeout(timer);
  }
}
