import { useCallback } from 'react';
import { createEntityHook } from './useEntityBase';
import { api } from '@/lib/api';
import { ENDPOINTS } from '@/constants/endpoints';
import i18n from "@/lib/i18n";

export type FractionalPoolDTO = {
  id: string;
  metal_type: string;
  purity_id: string;
  purity_name: string | null;
  vault_id: string | null;
  vault_name: string | null;
  physical_weight: number;
  allocated_client_weight: number;
  available_weight: number;
  reserved_weight: number;
  coverage_ratio: number;
  coverage_status: string;
  status: string;
  last_calculated_at: string | null;
  notes: string | null;
  created_at: string;
  updated_at: string;
};

export const useInventoryBase = createEntityHook<FractionalPoolDTO, never, never>(
  i18n.t('hooks.useInventory.text_1'),
  ENDPOINTS.INVENTORY.FRACTIONAL_POOLS,
);

export function useInventory() {
  const base = useInventoryBase();

  const addBarToPool = useCallback(async (poolId: string, barId: string, weight?: number) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const payload = { bar_id: barId, contributed_weight: weight };
      const res = await api.post(`${ENDPOINTS.INVENTORY.FRACTIONAL_POOLS}/${poolId}/bars`, payload);
      if (res.success) {
        await base.fetchItems();
        return true;
      }
      return false;
    } catch (err: any) {
      base.setError(err.message);
      return false;
    } finally {
      base.setIsLoading(false);
    }
  }, [base]);

  const removeBarFromPool = useCallback(async (poolId: string, barId: string, reason?: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const payload = { bar_id: barId, reason };
      const res = await api.post(`${ENDPOINTS.INVENTORY.FRACTIONAL_POOLS}/${poolId}/bars/remove`, payload);
      if (res.success) {
        await base.fetchItems();
        return true;
      }
      return false;
    } catch (err: any) {
      base.setError(err.message);
      return false;
    } finally {
      base.setIsLoading(false);
    }
  }, [base]);

  return {
    ...base,
    addBarToPool,
    removeBarFromPool,
  };
}
