const BASE = "";

export async function checkHealth() {
  const res = await fetch(`${BASE}/api/health`);
  if (!res.ok) throw new Error(`Health check failed: ${res.statusText}`);
  return res.json();
}

// ─── PostgreSQL ─────────────────────────────────────────────────────

export async function pgConnect(connectionString, label = "") {
  const res = await fetch(`${BASE}/api/pg/connect`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ connection_string: connectionString, label }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ detail: res.statusText }));
    throw new Error(err.detail || res.statusText);
  }
  return res.json();
}

export async function pgFetchTables(instanceId) {
  const res = await fetch(`${BASE}/api/pg/${encodeURIComponent(instanceId)}/tables`);
  if (!res.ok) throw new Error(`Failed to fetch tables: ${res.statusText}`);
  return res.json();
}

export async function pgFetchColumns(instanceId, schema, table) {
  const res = await fetch(`${BASE}/api/pg/${encodeURIComponent(instanceId)}/tables/${encodeURIComponent(schema)}/${encodeURIComponent(table)}/columns`);
  if (!res.ok) throw new Error(`Failed to fetch columns: ${res.statusText}`);
  return res.json();
}

export async function pgQuery(instanceId, { schema, table, include = "", exclude = "", highlight = "", columns = "", limit = 500, offset = 0, view_mode, aggregation, agg_column, group_by_column, value_column }) {
  const body = { schema, table, include, exclude, highlight, columns, limit, offset };
  if (view_mode) body.view_mode = view_mode;
  if (aggregation) body.aggregation = aggregation;
  if (agg_column) body.agg_column = agg_column;
  if (group_by_column) body.group_by_column = group_by_column;
  if (value_column) body.value_column = value_column;
  const res = await fetch(`${BASE}/api/pg/${encodeURIComponent(instanceId)}/query`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ detail: res.statusText }));
    throw new Error(err.detail || res.statusText);
  }
  return res.json();
}

// ─── BigQuery ────────────────────────────────────────────────────────

export async function bigqueryConnect({ project, dataset, credentialsPath, label = "" }) {
  const res = await fetch(`${BASE}/api/bigquery/connect`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      project,
      dataset,
      credentials_path: credentialsPath || "",
      label,
    }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ detail: res.statusText }));
    throw new Error(err.detail || res.statusText);
  }
  return res.json();
}

// ─── Redis ──────────────────────────────────────────────────────────

export async function redisConnect(connectionString, label = "") {
  const res = await fetch(`${BASE}/api/redis/connect`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ connection_string: connectionString, label }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ detail: res.statusText }));
    throw new Error(err.detail || res.statusText);
  }
  return res.json();
}

export async function redisQueryKeys(instanceId, { pattern = "*", offset = 0, limit = 100 }) {
  const res = await fetch(`${BASE}/api/redis/${encodeURIComponent(instanceId)}/keys`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ pattern, offset, limit }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ detail: res.statusText }));
    throw new Error(err.detail || res.statusText);
  }
  return res.json();
}

export async function redisGetKeyDetail(instanceId, key) {
  const res = await fetch(`${BASE}/api/redis/${encodeURIComponent(instanceId)}/keys/${encodeURIComponent(key)}`);
  if (!res.ok) {
    const err = await res.json().catch(() => ({ detail: res.statusText }));
    throw new Error(err.detail || res.statusText);
  }
  return res.json();
}

// ─── S3 ─────────────────────────────────────────────────────────────

export async function s3Connect({ endpointUrl, accessKey, secretKey, region, label = "" }) {
  const res = await fetch(`${BASE}/api/s3/connect`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      endpoint_url: endpointUrl,
      access_key: accessKey,
      secret_key: secretKey,
      region: region || "us-east-1",
      label,
    }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ detail: res.statusText }));
    throw new Error(err.detail || res.statusText);
  }
  return res.json();
}

export async function s3FetchBuckets(instanceId) {
  const res = await fetch(`${BASE}/api/s3/${encodeURIComponent(instanceId)}/buckets`);
  if (!res.ok) throw new Error(`Failed to fetch buckets: ${res.statusText}`);
  return res.json();
}

export async function s3QueryKeys(instanceId, { bucket, prefix = "", continuationToken = null, limit = 100 }) {
  const res = await fetch(`${BASE}/api/s3/${encodeURIComponent(instanceId)}/keys`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ bucket, prefix, continuation_token: continuationToken, limit }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ detail: res.statusText }));
    throw new Error(err.detail || res.statusText);
  }
  return res.json();
}

export async function s3GetKeyDetail(instanceId, bucket, key) {
  const res = await fetch(`${BASE}/api/s3/${encodeURIComponent(instanceId)}/keys/${encodeURIComponent(bucket)}/${encodeURIComponent(key)}`);
  if (!res.ok) {
    const err = await res.json().catch(() => ({ detail: res.statusText }));
    throw new Error(err.detail || res.statusText);
  }
  return res.json();
}
