import {
	type CustomerInfoModel,
	customerInfoModel,
	Gender,
} from "$lib/domains/customerinfo/data";
import { z } from "zod";

export class BillingDetailsViewModel {
	// @ts-ignore
	billingDetails = $state<CustomerInfoModel>(undefined);

	piiErrors = $state<Partial<Record<keyof CustomerInfoModel, string>>>({});

	constructor() {
		this.reset();
	}

	reset() {
		this.billingDetails = {
			firstName: "",
			middleName: "",
			lastName: "",
			email: "",
			phoneCountryCode: "",
			phoneNumber: "",
			passportNo: "",
			passportExpiry: "",
			nationality: "",
			gender: Gender.Male,
			dob: "",
			country: "",
			state: "",
			city: "",
			zipCode: "",
			address: "",
			address2: "",
		} as CustomerInfoModel;
		this.piiErrors = {};
	}

	setPII(info: CustomerInfoModel) {
		this.billingDetails = info;
	}

	validatePII(info: CustomerInfoModel) {
		try {
			const result = customerInfoModel.parse(info);
			this.piiErrors = {};
			return result;
		} catch (error) {
			if (error instanceof z.ZodError) {
				this.piiErrors = error.errors.reduce(
					(acc, curr) => {
						const path = curr.path[0] as keyof CustomerInfoModel;
						acc[path] = curr.message;
						return acc;
					},
					{} as Record<keyof CustomerInfoModel, string>,
				);
			}
			return null;
		}
	}

	isPIIValid(): boolean {
		return Object.keys(this.piiErrors).length === 0;
	}
}

export const billingDetailsVM = new BillingDetailsViewModel();
