import {
	type CardInfo,
	cardInfoModel,
} from "$lib/domains/paymentinfo/data/entities";
import { z } from "zod";

const _default = { cardholderName: "", cardNumber: "", expiry: "", cvv: "" };

class PaymentInfoViewModel {
	cardDetails = $state<CardInfo>({ ..._default });

	errors = $state<Partial<Record<keyof CardInfo, string>>>({});

	reset() {
		this.cardDetails = { ..._default };
		this.errors = {};
	}

	async validateAndSubmit() {
		try {
			const result = cardInfoModel.parse(this.cardDetails);
			this.errors = {};
			return result;
		} catch (error) {
			if (error instanceof z.ZodError) {
				this.errors = error.errors.reduce(
					(acc, curr) => {
						const path = curr.path[0] as keyof CardInfo;
						acc[path] = curr.message;
						return acc;
					},
					{} as Record<keyof CardInfo, string>,
				);
			}
			return null;
		}
	}
}

export const paymentInfoVM = new PaymentInfoViewModel();
