/**
 * Phoenix API Railing client — Infra, VE, Health, tenant-scoped.
 * Calls Sankofa API /api/v1/* (proxies to Phoenix Deploy API when PHOENIX_RAILING_URL is set).
 * Auth: Bearer token from NextAuth session (Keycloak/JWT) or X-API-Key.
 */

const getBaseUrl = () => {
  const g = process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT || '';
  if (g) return g.replace(/\/graphql\/?$/, '');
  return process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000';
};

type JsonObject = Record<string, unknown>;

function errorTextFromBody(body: unknown, fallback: string): string {
  if (body && typeof body === 'object') {
    const o = body as JsonObject;
    if (typeof o.message === 'string') return o.message;
    if (typeof o.error === 'string') return o.error;
  }
  return fallback;
}

export async function phoenixFetch<T>(
  path: string,
  token: string | undefined,
  options: RequestInit = {}
): Promise<T> {
  const base = getBaseUrl();
  const url = path.startsWith('http') ? path : `${base}${path}`;
  const res = await fetch(url, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...(token && { Authorization: `Bearer ${token}` }),
      ...options.headers,
    },
  });
  if (!res.ok) {
    const err: unknown = await res.json().catch(() => ({ error: res.statusText }));
    throw new Error(errorTextFromBody(err, res.statusText));
  }
  return res.json();
}

export async function getInfraNodes(token?: string) {
  return phoenixFetch<{ nodes: JsonObject[]; stub?: boolean }>('/api/v1/infra/nodes', token);
}

export async function getInfraStorage(token?: string) {
  return phoenixFetch<{ storage: JsonObject[]; stub?: boolean }>('/api/v1/infra/storage', token);
}

export async function getVMs(token?: string, node?: string) {
  const qs = node ? `?node=${encodeURIComponent(node)}` : '';
  return phoenixFetch<{ vms: JsonObject[]; stub?: boolean }>(`/api/v1/ve/vms${qs}`, token);
}

export async function getVMStatus(node: string, vmid: string, token?: string, type: 'qemu' | 'lxc' = 'qemu') {
  return phoenixFetch<{ node: string; vmid: string; status?: string }>(
    `/api/v1/ve/vms/${node}/${vmid}/status?type=${type}`,
    token
  );
}

export async function vmAction(node: string, vmid: string, action: 'start' | 'stop' | 'reboot', token?: string, type: 'qemu' | 'lxc' = 'qemu') {
  return phoenixFetch<{ ok: boolean }>(`/api/v1/ve/vms/${node}/${vmid}/${action}?type=${type}`, token, { method: 'POST' });
}

export async function getHealthSummary(token?: string) {
  return phoenixFetch<{ status: string; updated_at: string; hosts: JsonObject[]; alerts: JsonObject[] }>(
    '/api/v1/health/summary',
    token
  );
}

export async function getHealthAlerts(token?: string) {
  return phoenixFetch<{ alerts: JsonObject[] }>('/api/v1/health/alerts', token);
}

export async function getTenantResources(token?: string) {
  return phoenixFetch<{ resources: JsonObject[]; tenantId: string }>('/api/v1/tenants/me/resources', token);
}

export async function getTenantHealth(token?: string) {
  return phoenixFetch<{ tenantId: string; status: string }>('/api/v1/tenants/me/health', token);
}
