/**
 * TanStack Query hooks for the /v1/tenants/* endpoints.
 *
 * The hooks are feature-scoped: callers (list, create-dialog,
 * detail-page) pull these and don't talk to fetchWithAuth
 * directly. That way the cache is shared across views and the
 * query keys are predictable.
 */

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { ApiError, apiGet, apiSend } from '@/lib/api';
import type {
  CreateTenantInput,
  ListTenantsResponse,
  Tenant,
  UpdateTenantInput,
} from './types';

export interface ListTenantsParams {
  q?: string;
  status?: string;
  limit?: number;
  offset?: number;
}

const KEYS = {
  list: (params: ListTenantsParams) => ['tenants', 'list', params] as const,
  detail: (id: string | undefined) => ['tenants', 'detail', id] as const,
};

function buildListQuery(params: ListTenantsParams): string {
  const u = new URLSearchParams();
  if (params.q) u.set('q', params.q);
  if (params.status) u.set('status', params.status);
  if (params.limit) u.set('limit', String(params.limit));
  if (params.offset) u.set('offset', String(params.offset));
  const s = u.toString();
  return s ? `/v1/tenants?${s}` : '/v1/tenants';
}

export function useTenantsList(params: ListTenantsParams) {
  return useQuery({
    queryKey: KEYS.list(params),
    queryFn: () => apiGet<ListTenantsResponse>(buildListQuery(params)),
    // Tenant_admin scoping is enforced server-side; we still want
    // refetch when the user switches to/from super_admin context.
    staleTime: 15_000,
  });
}

export function useTenant(id: string | undefined) {
  return useQuery({
    queryKey: KEYS.detail(id),
    queryFn: () => apiGet<Tenant>(`/v1/tenants/${id}`),
    enabled: Boolean(id),
  });
}

export function useCreateTenant() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (input: CreateTenantInput) =>
      apiSend<Tenant>('POST', '/v1/tenants', input),
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: ['tenants', 'list'] });
    },
  });
}

export function useUpdateTenant(id: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (input: UpdateTenantInput) =>
      apiSend<Tenant>('PATCH', `/v1/tenants/${id}`, input),
    onSuccess: (tenant) => {
      qc.setQueryData(KEYS.detail(id), tenant);
      void qc.invalidateQueries({ queryKey: ['tenants', 'list'] });
    },
  });
}

export function useSetTenantStatus(id: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (status: 'active' | 'suspended' | 'archived') =>
      apiSend<Tenant>('POST', `/v1/tenants/${id}/status`, { status }),
    onSuccess: (tenant) => {
      qc.setQueryData(KEYS.detail(id), tenant);
      void qc.invalidateQueries({ queryKey: ['tenants', 'list'] });
    },
  });
}

export function getErrorMessage(err: unknown): string {
  if (err instanceof ApiError) {
    const body = err.body as { error?: string; message?: string } | null;
    return body?.message ?? body?.error ?? err.message;
  }
  if (err instanceof Error) return err.message;
  return 'Unknown error';
}
