import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from './client';
import type { VendorTenantSummary, VendorTenantDetail, CreateTenantRequest, TenantResponse, LicenseResponse } 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) {
  return useQuery<VendorTenantDetail>({
    queryKey: ['vendor', 'tenants', id],
    queryFn: () => api.get(`/vendor/tenants/${id}`),
    enabled: !!id,
  });
}

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 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] }),
  });
}
