// store/withdrawalStore.ts import { create } from "zustand"; interface Withdrawal { id: number; user: string; created_at: string; amount: number; status: "pending" | "paid" | "cancelled"; note: string; } interface WithdrawalData { success: boolean; page: number; limit: number; total: number; data: Withdrawal[]; } interface WithdrawalState { withdrawals: WithdrawalData | null; isLoading: boolean; error: string | null; // Actions fetchWithdrawals: (page?: number, limit?: number) => Promise; requestWithdrawal: ( amount: number, note: string ) => Promise<{ success: boolean; error?: string }>; clearData: () => void; clearError: () => void; } const API_BASE_URL = import.meta.env.VITE_SERVER_URL; export const useWithdrawalStore = create((set) => ({ withdrawals: null, isLoading: false, error: null, fetchWithdrawals: async (page = 1, limit = 10) => { set({ isLoading: true, error: null }); try { // Get token from localStorage const token = localStorage.getItem("aff-token"); if (!token) { throw new Error("No authentication token found"); } const response = await fetch( `${API_BASE_URL}/affiliate/withdraw/my-withdraws?page=${page}&limit=${limit}`, { method: "GET", headers: { accept: "*/*", Authorization: `Bearer ${token}`, }, } ); if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error(errorData.message || "Failed to fetch withdrawals"); } const data = await response.json(); set({ withdrawals: data, isLoading: false, error: null, }); } catch (error) { console.error("Fetch withdrawals error:", error); set({ isLoading: false, error: error instanceof Error ? error.message : "Failed to fetch withdrawals", }); } }, requestWithdrawal: async (amount: number, note: string) => { set({ isLoading: true, error: null }); try { const token = localStorage.getItem("aff-token"); if (!token) { throw new Error("No authentication token found"); } const response = await fetch( `${API_BASE_URL}/affiliate/withdraw/request`, { method: "POST", headers: { accept: "*/*", Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, body: JSON.stringify({ amount, note, }), } ); if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error(errorData.message || "Failed to request withdrawal"); } await response.json(); set({ isLoading: false, error: null, }); return { success: true }; } catch (error) { console.error("Request withdrawal error:", error); set({ isLoading: false, error: error instanceof Error ? error.message : "Failed to request withdrawal", }); return { success: false, error: error instanceof Error ? error.message : "Failed to request withdrawal", }; } }, clearData: () => { set({ withdrawals: null, error: null, }); }, clearError: () => { set({ error: null }); }, }));