import { goto } from "$app/navigation";
import { get } from "svelte/store";
import { authClient } from "../config/client";
import { authPayloadModel, type AuthPayloadModel } from "../data/entities";
import { toast } from "svelte-sonner";
import { trpcApiStore } from "$lib/stores/api";

export class AuthViewModel {
	submitting = $state(false);

	onAuthFormSubmit = async (event: SubmitEvent) => {
		event.preventDefault();
		const form = event.target as HTMLFormElement;
		const formData = new FormData(form);
		const res = authPayloadModel.safeParse(
			Object.fromEntries(formData.entries()),
		);
		if (!res.success) {
			const field = res.error.errors[0].path[0].toString();
			const msg = res.error.errors[0].message;
			return toast.error(`${field} ${msg}`);
		}
		this.submitting = true;
		const ok = await this.authenticate(res.data);
		this.submitting = false;
		if (!ok) {
			return;
		}
		form.reset();
		setTimeout(() => goto("/"), 1000);
	};

	async authenticate(payload: AuthPayloadModel) {
		const api = get(trpcApiStore);
		if (!api) {
			toast.error(
				"Could not authenticate at the moment, please try again later",
			);
			return false;
		}
		const out = await api.auth.shouldLogin.query({
			username: payload.username,
		});
		console.log("yeee");
		console.log("out : ", out);

		if (typeof out.data !== "boolean") {
			toast.error(
				"Could not authenticate at the moment, please try again later",
			);
			return false;
		}
		if (!out.data) {
			toast.error("Invalid username or password");
			return false;
		}
		const { data, error } = await authClient.signIn.username(payload);
		if (error) {
			toast.error(error.message ?? "An error occurred");
			return false;
		}
		if (data && data.user) {
			toast.success("Login Successful, Redirecting...");
			return true;
		}
		toast.error("An error occurred while logging in, please try again");
		return false;
	}
}

export const authVM = new AuthViewModel();
