import { createSharedComposable } from "@vueuse/core";

export type BiddingItem = {
  id: number;
  name: string;
  startPrice: number;
  remarks: string;
  imageUrl?: string;
};

const _useBiddingItems = () => {
  const biddingItems = ref<BiddingItem[]>([]);

  const biddingItemsLatestId = computed(() => {
    const arr = biddingItems.value ?? [];
    if (arr.length === 0) return 1;
    return Math.max(...arr.map((i) => i.id)) + 1;
  });

  const addBiddingItem = (item: Item, startPrice: number) => {
    biddingItems.value.push({
      id: biddingItemsLatestId.value,
      name: `${item.brand} ${item.name}`,
      startPrice: startPrice,
      remarks: "",
      imageUrl: item.imageUrl,
    });
  };

  const removeBiddingItem = (id: number) => {
    biddingItems.value = (biddingItems.value ?? []).filter((i) => i.id !== id);
  };

  const editBiddingItem = (biddingItem: BiddingItem) => {
    const idx = (biddingItems.value ?? []).findIndex(
      (i) => i.id === biddingItem.id
    );
    if (idx === -1) return;
    const updatedBiddingItems = [...(biddingItems.value ?? [])];
    updatedBiddingItems[idx] = {
      ...updatedBiddingItems[idx],
      ...biddingItem,
    };
    biddingItems.value = updatedBiddingItems;
  };

  return { biddingItems, addBiddingItem, removeBiddingItem, editBiddingItem };
};

export const useBiddingItems = createSharedComposable(_useBiddingItems);
