import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from './client';
import type { VendorTenantSummary, VendorTenantDetail, CreateTenantRequest, TenantResponse, LicenseResponse, AuditLogPage, AuditLogFilters, TenantMetricsEntry } from '../types/api';

export function useVendorTenants() {
  return useQuery<VendorTenantSummary[]>({
    queryKey: ['vendor', 'tenants'],
    queryFn: () => api.get('/vendor/tenants'),
    refetchInterval: 30_000,
  });
}

export function useVendorTenant(
  id: string | null,
  options?: { refetchInterval?: number | false | ((query: { state: { data: VendorTenantDetail | undefined } }) => number | false) },
) {
  return useQuery<VendorTenantDetail>({
    queryKey: ['vendor', 'tenants', id],
    queryFn: () => api.get(`/vendor/tenants/${id}`),
    enabled: !!id,
    refetchInterval: options?.refetchInterval as any,
  });
}

export function useCreateTenant() {
  const qc = useQueryClient();
  return useMutation<TenantResponse, Error, CreateTenantRequest>({
    mutationFn: (req) => api.post('/vendor/tenants', req),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['vendor', 'tenants'] }),
  });
}

export function useSuspendTenant() {
  const qc = useQueryClient();
  return useMutation<TenantResponse, Error, string>({
    mutationFn: (id) => api.post(`/vendor/tenants/${id}/suspend`),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['vendor', 'tenants'] }),
  });
}

export function useActivateTenant() {
  const qc = useQueryClient();
  return useMutation<TenantResponse, Error, string>({
    mutationFn: (id) => api.post(`/vendor/tenants/${id}/activate`),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['vendor', 'tenants'] }),
  });
}

export function useDeleteTenant() {
  const qc = useQueryClient();
  return useMutation<void, Error, string>({
    mutationFn: (id) => api.delete(`/vendor/tenants/${id}`),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['vendor', 'tenants'] }),
  });
}

export function useRestartServer() {
  const qc = useQueryClient();
  return useMutation<void, Error, string>({
    mutationFn: (id) => api.post(`/vendor/tenants/${id}/restart`),
    onSuccess: (_, id) => qc.invalidateQueries({ queryKey: ['vendor', 'tenants', id] }),
  });
}

export function useUpgradeServer() {
  const qc = useQueryClient();
  return useMutation<void, Error, string>({
    mutationFn: (id) => api.post(`/vendor/tenants/${id}/upgrade`),
    onSuccess: (_, id) => qc.invalidateQueries({ queryKey: ['vendor', 'tenants', id] }),
  });
}

export function useRenewLicense() {
  const qc = useQueryClient();
  return useMutation<LicenseResponse, Error, string>({
    mutationFn: (tenantId) => api.post(`/vendor/tenants/${tenantId}/license`),
    onSuccess: (_, tenantId) => qc.invalidateQueries({ queryKey: ['vendor', 'tenants', tenantId] }),
  });
}

export function useVendorAuditLog(filters: AuditLogFilters) {
  const params = new URLSearchParams();
  if (filters.tenantId) params.set('tenantId', filters.tenantId);
  if (filters.action) params.set('action', filters.action);
  if (filters.result) params.set('result', filters.result);
  if (filters.search) params.set('search', filters.search);
  if (filters.from) params.set('from', filters.from);
  if (filters.to) params.set('to', filters.to);
  params.set('page', String(filters.page ?? 0));
  params.set('size', String(filters.size ?? 25));

  return useQuery<AuditLogPage>({
    queryKey: ['vendor', 'audit', filters],
    queryFn: () => api.get(`/vendor/audit?${params.toString()}`),
  });
}

// --- Infrastructure ---

export interface PostgresOverview {
  version: string;
  databaseSizeBytes: number;
  activeConnections: number;
}

export interface TenantPgStats {
  slug: string;
  schemaSizeBytes: number;
  tableCount: number;
  totalRows: number;
}

export interface TableStats {
  tableName: string;
  rowCount: number;
  dataSizeBytes: number;
  indexSizeBytes: number;
}

export interface ClickHouseOverview {
  version: string;
  uptimeSeconds: number;
  totalDiskBytes: number;
  totalUncompressedBytes: number;
  compressionRatio: number;
  totalRows: number;
  activeMerges: number;
}

export interface TenantChStats {
  tenantId: string;
  totalRows: number;
  rowsByTable: Record<string, number>;
}

export interface ChTableStats {
  tableName: string;
  rowCount: number;
}

export interface InfraOverview {
  postgres: PostgresOverview;
  clickhouse: ClickHouseOverview;
}

export function useInfraOverview() {
  return useQuery<InfraOverview>({
    queryKey: ['vendor', 'infrastructure'],
    queryFn: () => api.get('/vendor/infrastructure'),
  });
}

export function useInfraPostgres() {
  return useQuery<{ overview: PostgresOverview; tenants: TenantPgStats[] }>({
    queryKey: ['vendor', 'infrastructure', 'postgres'],
    queryFn: () => api.get('/vendor/infrastructure/postgres'),
  });
}

export function useInfraClickHouse() {
  return useQuery<{ overview: ClickHouseOverview; tenants: TenantChStats[] }>({
    queryKey: ['vendor', 'infrastructure', 'clickhouse'],
    queryFn: () => api.get('/vendor/infrastructure/clickhouse'),
  });
}

export function useInfraPgDetail(slug: string) {
  return useQuery<TableStats[]>({
    queryKey: ['vendor', 'infrastructure', 'postgres', slug],
    queryFn: () => api.get(`/vendor/infrastructure/postgres/${slug}`),
    enabled: !!slug,
  });
}

export function useInfraChDetail(tenantId: string) {
  return useQuery<ChTableStats[]>({
    queryKey: ['vendor', 'infrastructure', 'clickhouse', tenantId],
    queryFn: () => api.get(`/vendor/infrastructure/clickhouse/${tenantId}`),
    enabled: !!tenantId,
  });
}

// --- Tenant Metrics ---

export function useTenantMetrics() {
  return useQuery<TenantMetricsEntry[]>({
    queryKey: ['vendor', 'metrics'],
    queryFn: () => api.get('/vendor/metrics'),
    refetchInterval: 60_000,
  });
}
