import { apiFetch } from '$lib/utils/api';

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 load() {
		if (loading) return;
		loading = true;
		try {
			const res = await apiFetch('/api/user/payment-methods');
			if (res.ok) {
				cards = await res.json();
			} else {
				cards = [];
			}
			loaded = true;
		} catch {
			cards = [];
		} finally {
			loading = false;
		}
	}

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

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

export const savedCardsStore = createSavedCardsStore();
