import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from './client';

export interface CaCertResponse {
  id: string;
  status: string;
  label: string | null;
  subject: string;
  issuer: string;
  fingerprint: string;
  notBefore: string;
  notAfter: string;
  createdAt: string;
}

export function useTenantCaCerts() {
  return useQuery<CaCertResponse[]>({
    queryKey: ['tenant', 'ca'],
    queryFn: () => api.get('/tenant/ca'),
  });
}

export function useStageCaCert() {
  const qc = useQueryClient();
  return useMutation<CaCertResponse, Error, FormData>({
    mutationFn: (formData) => api.post('/tenant/ca', formData),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['tenant', 'ca'] }),
  });
}

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

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