import { trpcApiStore } from "$lib/stores/api";
import { toast } from "svelte-sonner";
import { get } from "svelte/store";
import { authClient } from "../../config/client";

export class SecurityViewModel {
	previousPassword = $state("");
	newPassword = $state("");
	confirmPassword = $state("");
	submitting = $state(false);

	async confirmAndSumbit() {
		const api = get(trpcApiStore);
		if (!api) {
			return toast.error("Could not connect to server", {
				description:
					"Please refresh page and try again, otherwise contact us",
			});
		}
		this.submitting = true;
		const res = await authClient.changePassword({
			currentPassword: this.previousPassword,
			newPassword: this.newPassword,
			revokeOtherSessions: true,
		});
		this.submitting = false;
		console.log(res);
		if (res.error) {
			return toast.error(
				res.error.message ??
					"Could not change password at this moment, please try again later",
			);
		}
		toast.success("Password has been changed successfully");
		this.previousPassword = "";
		this.newPassword = "";
		this.confirmPassword = "";
	}
}

export const securityVM = new SecurityViewModel();
