import type { ApiSettings } from "../types";
import { apiFetch, apiGetList } from "./client";

export type PermissionItem = {
  scope: string;
  label: string;
  description: string;
  category: string;
  level: "tenant" | "system";
  system_template_id?: string | null;
  system_required?: boolean;
};

export type AdminOverview = {
  active_tenant_id: string;
  active_tenant_name: string;
  tenant_count?: number | null;
  system_account_count?: number | null;
  system_group_template_count?: number | null;
  system_role_template_count?: number | null;
  user_count: number;
  active_user_count: number;
  group_count: number;
  role_count: number;
  active_api_key_count: number;
  capabilities: string[];
};

export type TenantAdminItem = {
  id: string;
  slug: string;
  name: string;
  description?: string | null;
  default_locale: string;
  settings: Record<string, unknown>;
  allow_custom_groups?: boolean | null;
  allow_custom_roles?: boolean | null;
  allow_api_keys?: boolean | null;
  effective_governance: Record<string, boolean>;
  is_active: boolean;
  counts: Record<string, number>;
  created_at: string;
  updated_at: string;
};

export function fetchAdminOverview(settings: ApiSettings): Promise<AdminOverview> {
  return apiFetch(settings, "/api/v1/admin/overview");
}

export async function fetchPermissionCatalog(settings: ApiSettings): Promise<PermissionItem[]> {
  return apiGetList<PermissionItem, "permissions">(settings, "/api/v1/admin/permissions", "permissions");
}

export async function fetchTenants(settings: ApiSettings): Promise<TenantAdminItem[]> {
  return apiGetList<TenantAdminItem, "tenants">(settings, "/api/v1/admin/tenants", "tenants");
}
