// Fetches StaffLDB Data, correctly formats DATE fields and returns the data

import { getApiUrl } from "$lib/scripts/upstream";
import { uuid } from "$lib/stores/uuid";
import type { ApiResponse, StaffLdb } from "@owlboard/ts-types";

// Fetch StaffLDB Data, and returns the data after hydration (convert date types etc.)
export async function fetchStaffLdb(station: string): Promise<ApiResponse<StaffLdb>> {
    const url = `${getApiUrl()}/api/v2/live/station/${station}/staff`;

    let uuid_value: string = "";
    const unsubscribe = uuid.subscribe((value) => {
        uuid_value = value;
    });

    const fetchOpts = {
        method: "GET",
        headers: {
            uuid: uuid_value,
        },
    };
    const res = await fetch(url, fetchOpts);
    unsubscribe();
    const resJs = await res.json();
    return parseFormat(JSON.stringify(resJs));
}

// Parse dates within the JSON response
function parseFormat(jsonString: any): ApiResponse<StaffLdb> {
    return JSON.parse(jsonString, (key, value) => {
        if (typeof value === "string") {
            const dateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/;
            if (dateRegex.test(value)) {
                return new Date(value);
            }
        }
        return value;
    });
}
