import { BatchPromotion, BatchPromotionMember } from '@shared/schemas/promotionSchema';
import { PagedData } from '@shared/types/pagination';
import { PromotionDetails, PromotionSummary, Rank } from '@shared/types/rank'

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

export async function getAllRanks(): Promise<Rank[]> {
    const res = await fetch(`${addr}/ranks`, {
        credentials: 'include'
    })

    if (res.ok) {
        return res.json()
    } else {
        console.error("Something went wrong approving the application")
    }
}

export async function submitRankChange(promo: BatchPromotion) {
    const res = await fetch(`${addr}/memberRanks`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        credentials: 'include',
        body: JSON.stringify(promo),
    })

    if (res.ok) {
        return
    } else {
        throw new Error("Failed to submit rank change: Server error");
    }
}

export async function getPromoHistory(page?: number, pageSize?: number): Promise<PagedData<PromotionSummary>> {
    const params = new URLSearchParams();

    if (page !== undefined) {
        params.set("page", page.toString());
    }

    if (pageSize !== undefined) {
        params.set("pageSize", pageSize.toString());
    }

    return fetch(`${addr}/memberRanks?${params}`, {
        method: "GET",
        headers: {
            "Content-Type": "application/json",
        },
        credentials: 'include',
    }).then((res) => {
        if (res.ok) {
            return res.json();
        } else {
            return [];
        }
    });
}

export async function getPromotionsOnDay(day: Date): Promise<PromotionDetails[]> {
    const res = await fetch(`${addr}/memberRanks/${day.toISOString()}`, {
        credentials: 'include',
    })

    if (res.ok) {
        return await res.json();
    } else {
        throw new Error("Failed to submit rank change: Server error");
    }
}