import { checkLinkValiditySQ, resolveLinkSQ } from "./link.remote";
import type { Err } from "@pkg/result";

export type SessionEndReason =
    | "missing_token"
    | "invalid"
    | "expired"
    | "revoked"
    | "busy"
    | "not_found"
    | "network"
    | "unknown";

export async function resolveLinkFresh(token: string) {
    const query = resolveLinkSQ({ token });

    if (query.ready) {
        await query.refresh();
        return query.current;
    }

    return await query;
}

export async function checkLinkValidityFresh(token: string) {
    const query = checkLinkValiditySQ({ token });

    if (query.ready) {
        await query.refresh();
        return query.current;
    }

    return await query;
}

export function mapLinkErrorToSessionEndReason(
    error?: Pick<Err, "code" | "message" | "description"> | null,
): SessionEndReason {
    if (!error) return "unknown";

    const text = `${error.code} ${error.message} ${error.description}`.toLowerCase();

    if (text.includes("expired")) return "expired";
    if (text.includes("revoked")) return "revoked";
    if (text.includes("not found")) return "not_found";
    if (text.includes("busy") || text.includes("offline")) return "busy";
    if (text.includes("invalid") || text.includes("token")) return "invalid";

    return "unknown";
}
