import { authClient } from "$lib/auth.client";
import { toast } from "svelte-sonner";
import { ResultAsync, errAsync, okAsync } from "neverthrow";
import type { Err } from "@pkg/result";

class AuthViewModel {
    loggingIn = $state(false);

    async loginWithCredentials(data: FormData): Promise<boolean> {
        const username = data.get("username")?.toString().trim();
        const password = data.get("password")?.toString();

        if (!username || username.length < 3) {
            toast.error("Please enter a valid username");
            return false;
        }

        if (!password || password.length < 6) {
            toast.error("Please enter a valid password");
            return false;
        }

        this.loggingIn = true;

        const result = await ResultAsync.fromPromise(
            authClient.signIn.username({ username, password }),
            (error): Err => ({
                code: "NETWORK_ERROR",
                message: "Failed to login",
                description: "Network request failed",
                detail: error instanceof Error ? error.message : String(error),
            }),
        )
            .andThen((response) => {
                if (response.error) {
                    return errAsync({
                        code: "API_ERROR",
                        message: response.error.message ?? "Invalid credentials",
                        description:
                            response.error.statusText ??
                            "Please check your username and password",
                        detail: response.error.statusText ?? "Unknown error",
                    });
                }
                return okAsync(response.data);
            });

        const success = result.match(
            () => {
                toast.success("Login successful", {
                    description: "Redirecting...",
                });
                setTimeout(() => {
                    window.location.href = "/";
                }, 500);
                return true;
            },
            (error) => {
                toast.error(error.message ?? "Invalid credentials", {
                    description: error.description,
                });
                return false;
            },
        );

        this.loggingIn = false;
        return success;
    }
}

export const authVM = new AuthViewModel();
