interface BaserowRow {
  id: number;
  [key: string]: unknown;
}

export async function fetchBaserowRows<T extends BaserowRow>(
  tableId: string | number,
): Promise<T[]> {
  const apiUrl =
    import.meta.env.BASEROW_API_URL || "https://api.baserow.io";
  const token = import.meta.env.BASEROW_API_TOKEN;

  if (!token) {
    throw new Error(
      "BASEROW_API_TOKEN environment variable is not set",
    );
  }

  const url = new URL(
    `${apiUrl}/api/database/rows/table/${tableId}/`,
  );
  url.searchParams.set("user_field_names", "true");
  url.searchParams.set("size", "200");

  const res = await fetch(url.toString(), {
    headers: { Authorization: `Token ${token}` },
  });

  if (!res.ok) {
    throw new Error(
      `Baserow API error: ${res.status} ${res.statusText}`,
    );
  }

  const data = await res.json();
  return data.results as T[];
}

export async function createBaserowRow(
  tableId: string | number,
  fields: Record<string, unknown>,
): Promise<{ id: number }> {
  const apiUrl =
    import.meta.env.BASEROW_API_URL || "https://api.baserow.io";
  const token = import.meta.env.BASEROW_API_TOKEN;

  if (!token) {
    throw new Error("BASEROW_API_TOKEN environment variable is not set");
  }

  const url = new URL(`${apiUrl}/api/database/rows/table/${tableId}/`);
  url.searchParams.set("user_field_names", "true");

  const res = await fetch(url.toString(), {
    method: "POST",
    headers: {
      Authorization: `Token ${token}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(fields),
  });

  if (!res.ok) {
    throw new Error(`Baserow API error: ${res.status} ${res.statusText}`);
  }

  return res.json() as Promise<{ id: number }>;
}
