import { toast } from "svelte-sonner";
import { emailModel, type UserModel } from "../../data/entities";
import { authClient } from "$lib/domains/auth/config/client";

export class ProfileInfoViewModel {
	userInfo = $state<UserModel | undefined>();

	updating = $state(false);

	async onProfileInfoFormSubmit(event: Event) {
		event.preventDefault();
		if (!this.userInfo) {
			return toast.error("User not found", {
				description: "Please try again after refreshing page",
			});
		}
		// @ts-ignore
		const email = event.currentTarget.elements.email.value;
		const parsed = emailModel.safeParse(email);
		if (!parsed.success) {
			const _err = parsed.error.errors[0];
			const msg = `${_err.path[0]} ${_err.message}`;
			toast.error(msg ?? "Please fill in all the required fields");
			return false;
		}
		this.updating = true;
		const { error, data } = await authClient.changeEmail({ newEmail: email });
		this.updating = false;
		if (error || !data.status) {
			return toast.error(
				error?.message ??
					"An error occurred while saving info, please try again later",
			);
		}
		toast.success("Changes have been saved, Logging out");

		await authClient.signOut();
		window.location.reload();
	}
}

export const profileInfoVM = new ProfileInfoViewModel();
