import { memberSettings, Member, MemberLight } from "@shared/types/member";

//  @ts-ignore
const addr = import.meta.env.VITE_APIHOST;

export async function getMembers(): Promise<Member[]> {
    const response = await fetch(`${addr}/members`, {
        credentials: 'include'
    });
    if (!response.ok) {
        throw new Error("Failed to fetch members");
    }
    return response.json();
}

export async function getMemberSettings(): Promise<memberSettings> {
    const response = await fetch(`${addr}/members/settings`, {
        credentials: 'include'
    });
    if (!response.ok) {
        throw new Error("Failed to fetch settings");
    }
    return response.json();
}

export async function setMemberSettings(settings: memberSettings) {
    const response = await fetch(`${addr}/members/settings`, {
        credentials: 'include',
        method: 'PUT',
        headers: {
            'Content-Type': 'Application/json',
        },
        body: JSON.stringify(settings)
    });
    if (!response.ok) {
        throw new Error("Failed to fetch settings");
    }
    return;
}

export async function getLightMembers(ids: number[]): Promise<MemberLight[]> {

    if (ids.length === 0) return [];

    const response = await fetch(`${addr}/members/lite/bulk`, {
        credentials: 'include',
        method: 'POST',
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ ids })
    });

    if (!response.ok) {
        throw new Error("Failed to fetch light members");
    }
    return response.json();
}

export async function getFullMembers(ids: number[]): Promise<Member[]> {

    if (ids.length === 0) return [];

    const response = await fetch(`${addr}/members/full/bulk`, {
        credentials: 'include',
        method: 'POST',
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ ids })
    });
    if (!response.ok) {
        throw new Error("Failed to fetch settings");
    }
    return response.json();
}