import apiClient from '@/services/axiosSetup';
import {Space} from "@/models/Space";
import {useSpaceStore} from "@/stores/spaceStore";

export const getSpaces = async () => {
    return await apiClient.get('/spaces').then((res) => {
        res.data.forEach((space: Space) => {
            space.createdAt = new Date(space.createdAt);
        })
        return res.data
    });
}

export const createSpaceRequest = async (space: Space) => {
    return await apiClient.post('/spaces', space).then((res) => {
        return res.data
    }).catch((err) => {
        throw err
    });
}


export const deleteSpaceRequest = async (spaceId: string) => {
    return await apiClient.delete(`/spaces/${spaceId}`).then((res) => {
        return res.data
    }).catch((err) => {
        throw err
    });
}


export const createSpaceInvite = async () => {
    const spaceStore = useSpaceStore();
    return await apiClient.post(`/spaces/${spaceStore.space?.id}/invite`).then((res) => res.data)
}

export const acceptInviteRequest = async (code:string) => {
    await apiClient.post(`spaces/invite/${code}`).then((res) => res.data).catch((err) => {throw err})
}

export const leaveSpaceRequest = async (spaceId:string) => {
    await apiClient.delete(`spaces/${spaceId}/leave`).then((res) => res.data).catch((err) => {throw err})
}

export const kickMemberFromSpaceRequest = async (spaceId:string, username: string) => {
    await apiClient.delete(`spaces/${spaceId}/members/kick/${username}`).then((res) => res.data).catch((err) => {throw err})
}