import { create } from "zustand";
import type { CouponStrategy } from "@/lib/api/predictions/types";
import type { CouponItemDto } from "@/lib/api/coupons/types";

interface CouponState {
  strategy: CouponStrategy;
  items: CouponItemDto[];
  isBuilding: boolean;
}

interface CouponActions {
  setStrategy: (strategy: CouponStrategy) => void;
  addItem: (item: CouponItemDto) => void;
  removeItem: (matchId: string) => void;
  clearCoupon: () => void;
  setIsBuilding: (isBuilding: boolean) => void;
}

type CouponStore = CouponState & CouponActions;

const initialState: CouponState = {
  strategy: "BALANCED",
  items: [],
  isBuilding: false,
};

export const useCouponStore = create<CouponStore>()((set) => ({
  ...initialState,

  setStrategy: (strategy) => set({ strategy }),

  addItem: (item) =>
    set((state) => {
      // Prevent duplicate match entries
      const exists = state.items.some((i) => i.matchId === item.matchId);
      if (exists) return state;
      return { items: [...state.items, item] };
    }),

  removeItem: (matchId) =>
    set((state) => ({
      items: state.items.filter((i) => i.matchId !== matchId),
    })),

  clearCoupon: () => set(initialState),

  setIsBuilding: (isBuilding) => set({ isBuilding }),
}));
