import { getApiUrl } from "./scripts/upstream";
import { uuid } from "./stores/uuid";

export interface libauthResponse {
    uuidPresent?: boolean;
    serverAuthCheck?: boolean;
    uuidValue?: string;
    serverAuthCheckResponseCode?: number;
}

interface uuidCheckRes {
    uuidValue?: string;
    uuidPresent?: boolean;
}

export async function checkAuth(): Promise<libauthResponse> {
    let result: libauthResponse = {};
    const uuidCheck = await checkUuid();
    result.uuidPresent = uuidCheck?.uuidPresent;
    result.uuidValue = uuidCheck?.uuidValue;

    const serverCheck = await checkServerAuth(result.uuidValue || "");
    result.serverAuthCheck = serverCheck.authOk;
    result.serverAuthCheckResponseCode = serverCheck.status;

    return result;
}

async function checkUuid(): Promise<uuidCheckRes> {
    let uuid_value: string = "";
    const unsubscribe = uuid.subscribe((value) => {
        uuid_value = value;
    });
    let res: uuidCheckRes = {
        uuidValue: uuid_value,
    };
    console.log("uuid-value is: ", uuid_value);
    if (uuid_value && uuid_value != "null") {
        res = {
            uuidPresent: true,
            uuidValue: uuid_value,
        };
    } else {
        res = {
            uuidPresent: false,
            uuidValue: uuid_value,
        };
    }
    unsubscribe();
    return res;
}

async function checkServerAuth(uuidString: string) {
    const url = `${getApiUrl()}/api/v2/user/checkAuth`;
    const options = {
        method: "GET",
        headers: {
            uuid: uuidString,
        },
    };
    const res = await fetch(url, options);
    let ok: boolean;
    if (res.status !== 401) {
        ok = true;
    } else {
        ok = false;
    }
    return {
        authOk: ok,
        status: res.status,
    };
}

export async function logout(): Promise<boolean> {
    uuid.set(null);
    return true;
}
