const CMS_BASE_URL = process.env.NEXT_PUBLIC_CMS_BASE_URL?.replace(/\/$/, "");

export class CMSFetcher {
  private baseUrl: string;

  constructor(baseUrl: string | undefined = CMS_BASE_URL) {
    this.baseUrl = baseUrl ?? "";
  }

  async get<T>(path: string): Promise<T> {
    if (!this.baseUrl) {
      throw new Error(
        "Missing NEXT_PUBLIC_CMS_BASE_URL. Set it in apps/marketing-landing-page/.env.local",
      );
    }
    const normalizedPath = path.startsWith("/") ? path : `/${path}`;
    const url = `${this.baseUrl}${normalizedPath}`;

    const res = await fetch(url, { cache: "no-store" });

    if (!res.ok) {
      const text = await res.text().catch(() => "");
      throw new Error(`CMS request failed (${res.status}): ${text}`);
    }

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

export const cmsFetcher = new CMSFetcher();
