/* eslint-disable @typescript-eslint/no-explicit-any */
import { Client } from "@mescius/js-collaboration-client";
import { setLocalUser, userReq } from "./user";

function customFetch(url: string, init: RequestInit) {
    init.headers = {
        ...init.headers,
        'Authorization': `${userReq.currentUser()?.token}`
    };
    return fetch(url, init);
}

const serverUrl = (path: string) => {
    return `/api/` + path;
};

export function checkError(res: Response, json: any) {
    if (res.status === 401) {
        setLocalUser(null);
        location.replace('/login');
    }
    if (json.error) {
        throw json.error;
    }
}
const sanitizeFileName = (fileName: string) => {
    
    return fileName.replace(/[^a-zA-Z0-9.-_]/g, '_');
};
export const req = {
    get: (path: string) => customFetch(serverUrl(path), {}),
    post: (path: string, data: unknown) => customFetch(serverUrl(path), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }),
    upload: (path: string, file: File) => {
        const sanitizedFileName = sanitizeFileName(file.name);
        return customFetch(serverUrl(path), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/octet-stream',
                'X-File-Name': sanitizedFileName,
                'X-File-Type': file.type,
            },
            body: file,
        });
    },
};

export function connect(docId: string) {
    return new Client().connect(docId, { auth: { token: userReq.currentUser()?.token }});
}