import { useState } from "react"; import { useDeleteVendor } from "@/domain/vendors/use-cases/use-delete-vendor"; import { useVendorDeactivationImpact } from "@/domain/vendors/use-cases/use-vendor-deactivation-impact"; import type { VendorDeactivationImpact, VendorListItem } from "@/domain/vendors/types/vendor"; export interface VendorDeactivationState { target: VendorListItem | null; error: string | null; impact: VendorDeactivationImpact | undefined; isLoading: boolean; impactError: Error | null; isSaving: boolean; open: (row: VendorListItem) => void; close: () => void; confirm: () => void; } export function useVendorDeactivation(onSuccess?: () => void): VendorDeactivationState { const [target, setTarget] = useState(null); const [error, setError] = useState(null); const deleteVendor = useDeleteVendor(); const { data: impact, isLoading, error: impactError, } = useVendorDeactivationImpact(target?.id ?? undefined); const open = (row: VendorListItem) => { setTarget(row); setError(null); }; const close = () => { setTarget(null); setError(null); }; const confirm = () => { if (!target || target.id == null) return; setError(null); // The dialog has shown whatever open work orders exist, so confirming here is // the explicit confirmation the API requires to deactivate past them (SH-254). deleteVendor.mutate( { id: target.id, confirmOpenWorkOrders: (impact?.openWorkOrders.length ?? 0) > 0 }, { onSuccess: () => { setTarget(null); onSuccess?.(); }, onError: (err: Error) => setError(err.message || "Failed to deactivate vendor"), }, ); }; return { target, error, impact, isLoading, impactError, isSaving: deleteVendor.isPending, open, close, confirm, }; }