import { command, getRequestEvent, query } from '$app/server';
import { bookshelfCreate, bookshelfQuerySchema, modifyBooksInShelf, type Bookshelf } from '$lib/schema/bookshelf';
import { createQueryParams } from '$lib/utils';
import { error } from '@sveltejs/kit';

export const listBookshelves = query(bookshelfQuerySchema, async (data) => {
	const { locals } = getRequestEvent();

	const params = createQueryParams(data);

	const response = await locals.api.get(`/shelves?${params.toString()}`);

	if (!response.ok) {
		const message = await response.text();
		console.error('An unknown error occurred: ', message);
		error(500, 'An unkown error occurred');
	}

	return await response.json();
});

export const addBooksToShelf = command(modifyBooksInShelf, async ({ shelf_id, ...data }): Promise<Bookshelf> => {
	const { locals } = getRequestEvent();

	const params = createQueryParams(data);

	const response = await locals.api.post(`/shelves/${shelf_id}/books?${params.toString()}`, {});

	if (!response.ok) {
		const message = await response.text();
		error(response.status, message);
	}

	return await response.json()
});

export const removeBooksFromShelf = command(modifyBooksInShelf, async ({ shelf_id, ...data }): Promise<Bookshelf> => {
	const { locals } = getRequestEvent();

	const params = createQueryParams(data);

	const response = await locals.api.delete(`/shelves/${shelf_id}/books?${params.toString()}`);

	if (!response.ok) {
		const message = await response.text();
		error(response.status, message);
	}

	return await response.json()
});


export const createBookshelf = command(bookshelfCreate, async (data) => {
	const { locals } = getRequestEvent();

	const response = await locals.api.post(`/shelves`, data)

	if (!response.ok) {
		const message = await response.text();
		error(response.status, message);
	}

	return await response.json()
})
