import { http } from "../../services/http.service";

const apiPrefix = "/api/";

export const axiosDataProvider = {
	getList: async (resource, params) => {
		const { page, perPage } = params.pagination;
		// const { field, order } = params.sort;

		const skip = (page - 1) * perPage;

		// const { filter } = params;
		const query = {
			// _sort: field,
			// _order: order,
			skip: skip,
			take: perPage,
			// ...filter,
		};

		const response = await http.get(apiPrefix + resource, {
			params: query,
		});

		return {
			data: response.data.items,
			total: response.data.total,
		};
	},

	getOne: async (resource, params) => {
		const url = `${apiPrefix}${resource}/${params.id}`;
		const response = await http.get(url);
		return { data: response.data };
	},

	getMany: async (resource, params) => {
		const query = {
			id: params.ids,
		};
		const response = await http.get(apiPrefix + resource, {
			params: query,
		});
		return { data: response.data.items };
	},

	getManyReference: async (resource, params) => {
		const { page, perPage } = params.pagination;
		// const { field, order } = params.sort;

		const skip = (page - 1) * perPage;

		// const { filter } = params;
		const query = {
			// _sort: field,
			// _order: order,
			skip: skip,
			take: perPage,
			// ...filter,
			[params.target]: params.id,
		};

		const response = await http.get(apiPrefix + resource, {
			params: query,
		});

		return {
			data: response.data.items,
			total: response.data.total,
		};
	},

	update: async (resource, params) => {
		const url = `${apiPrefix}${resource}/${params.id}`;
		const response = await http.put(url, params.data);
		return { data: response.data };
	},

	updateMany: async (resource, params) => {
		const responses = await Promise.all(
			params.ids.map((id) =>
				http.put(`${apiPrefix}${resource}/${id}`, params.data)
			)
		);
		return { data: responses.map((response) => response.data) };
	},

	create: async (resource, params) => {
		const response = await http.post(apiPrefix + resource, params.data);
		return { data: { ...params.data, id: response.data.id } };
	},

	delete: async (resource, params) => {
		const url = `${apiPrefix}${resource}/${params.id}`;
		const response = await http.delete(url);
		return { data: response.data };
	},

	deleteMany: async (resource, params) => {
		const responses = await Promise.all(
			params.ids.map((id) => http.delete(`${apiPrefix}${resource}/${id}`))
		);
		return { data: responses.map((response) => response.data) };
	},
};
