import { Discharge } from "@shared/schemas/dischargeSchema";
import { memberSettings, Member, MemberLight, MemberCardDetails, PaginatedMembers, MemberState } 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 getMembersFiltered(params: {
    page?: number;
    pageSize?: number;
    search?: string;
    status?: string | MemberState;
    unitId?: string;
} = {}): Promise<PaginatedMembers> {

    // Construct the query string dynamically
    const query = new URLSearchParams();
    if (params.page) query.append('page', params.page.toString());
    if (params.pageSize) query.append('pageSize', params.pageSize.toString());
    if (params.search) query.append('search', params.search);
    if (params.status && params.status !== 'all') query.append('status', String(params.status));
    if (params.unitId && params.unitId !== 'all') query.append('unitId', params.unitId);

    const response = await fetch(`${addr}/members/filtered?${query.toString()}`, {
        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 getAllLightMembers(activeOnly: boolean = true): Promise<MemberLight[]> {
    const response = await fetch(`${addr}/members/lite${activeOnly ? '?active=true' : '?active=false'}`, {
        credentials: 'include',
        headers: {
            "Content-Type": "application/json",
        }
    });

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

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<MemberCardDetails[]> {

    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();
}

/**
 * Requests for the given member to be discharged
 * @param data discharge packet
 * @returns true on success
 */
export async function dischargeMember(data: Discharge): Promise<boolean> {
    const response = await fetch(`${addr}/members/discharge`, {
        credentials: 'include',
        method: 'POST',
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(data)
    });
    if (!response.ok) {
        throw new Error("Failed to discharge member");
    }
    return true;
}

export async function suspendMember(memberID: number): Promise<boolean> {
    const response = await fetch(`${addr}/members/suspend?target=${memberID}`, {
        credentials: 'include',
        method: 'POST',
    });
    if (!response.ok) {
        throw new Error("Failed to discharge member");
    }
    return true;
}

export async function unsuspendMember(memberID: number): Promise<boolean> {
    const response = await fetch(`${addr}/members/unsuspend?target=${memberID}`, {
        credentials: 'include',
        method: 'POST',
    });
    if (!response.ok) {
        throw new Error("Failed to discharge member");
    }
    return true;
}