export interface OrgClientOptions {
  baseUrl: string;
  productId: string;
  getAccessToken: () => string;
}

export interface OrgDoc {
  id: string;
  name: string;
  slug: string;
  memberCount: number;
  plan: string;
  metadata?: Record<string, unknown>;
}

function joinUrl(base: string, path: string): string {
  const b = base.replace(/\/$/, "");
  const p = path.startsWith("/") ? path : `/${path}`;
  return `${b}${p}`;
}

function headers(opts: OrgClientOptions): HeadersInit {
  return {
    Authorization: `Bearer ${opts.getAccessToken()}`,
    "X-Product-Id": opts.productId,
    Accept: "application/json",
  };
}

async function parseJson<T>(res: Response): Promise<T> {
  if (!res.ok) {
    const text = await res.text();
    throw new Error(`HTTP ${res.status}: ${text || res.statusText}`);
  }
  return res.json() as Promise<T>;
}

export function createOrgClient(opts: OrgClientOptions) {
  const { baseUrl } = opts;

  return {
    async listOrgs(): Promise<OrgDoc[]> {
      const res = await fetch(joinUrl(baseUrl, "/organizations"), {
        method: "GET",
        headers: headers(opts),
      });
      return parseJson<OrgDoc[]>(res);
    },

    async getOrg(orgId: string): Promise<OrgDoc> {
      const res = await fetch(
        joinUrl(baseUrl, `/organizations/${encodeURIComponent(orgId)}`),
        { method: "GET", headers: headers(opts) }
      );
      return parseJson<OrgDoc>(res);
    },
  };
}
