import { ApiError } from "@core/Models/Server.Error.model";

class ApiServerService {
    post<T>(endpoint: string, data: object): Promise<T> {
        return new Promise<T>((resolve, reject) => {
            const url = process.env.NEXT_PUBLIC_API_URL;
            fetch(`${url}${endpoint}`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(data),
                cache: "no-store",
            })
                .then((response) => {
                    resolve(response.json());
                })
                .catch((error) => {
                    try {
                        reject(new ApiError(error.response.data.code, error.response.data.desc));
                    } catch {
                        const errorMessage = process.env.VITE_API_UNAVAILABLE as string;
                        reject(new ApiError(500, errorMessage));
                    }
                });
        });
    }
}

const API_SERVER = new ApiServerService();

export default API_SERVER;
