export type SavedCard = {
	id: string;
	brand: string;
	last_4: string;
	exp_month: number;
	exp_year: number;
	cardholder_name?: string;
	is_default: boolean;
};

function createSavedCardsStore() {
	let cards = $state<SavedCard[]>([]);
	let loading = $state(false);
	let loaded = $state(false);

	async function fetch() {
		if (loading) return;
		loading = true;
		try {
			const headers: Record<string, string> = {};
			const token = globalThis.localStorage?.getItem('authToken');
			if (token) headers['Authorization'] = `Bearer ${token}`;
			const res = await globalThis.fetch('/api/user/payment-methods', { headers });
			if (res.ok) {
				cards = await res.json();
			} else {
				cards = [];
			}
			loaded = true;
		} catch {
			cards = [];
		} finally {
			loading = false;
		}
	}

	function invalidate() {
		loaded = false;
		return fetch();
	}

	return {
		get cards() {
			return cards;
		},
		get loading() {
			return loading;
		},
		get loaded() {
			return loaded;
		},
		fetch,
		invalidate
	};
}

export const savedCardsStore = createSavedCardsStore();
