import { command, form, getRequestEvent, query } from '$app/server';
import { error } from '@sveltejs/kit';
import {
	bookCoverUpload,
	booksUpload,
	bookIdsSchema,
	bookQuerySchema,
	deleteBookFilesSchema,
	deleteBooksSchema,
	editBookMetadataSchema,
	updateBookProgressSchema,
	type Book,
	bookFilesUpload
} from '$lib/schema/index';
import { stringCoerce, type PaginatedResponse } from '$lib/schema/common';
import { createQueryParams } from '$lib/utils';

export const getBook = query(stringCoerce, async (id): Promise<Book> => {
	const { locals } = getRequestEvent();

	const response = await locals.api.get(`/books/${id}`);

	if (!response.ok) {
		if (response.status == 404) error(404, 'The book does not exist');
		error(500, 'An unkown error occurred');
	}

	return await response.json();
});

export const listBooks = query(bookQuerySchema, async (data): Promise<PaginatedResponse<Book>> => {
	const { locals } = getRequestEvent();

	const params = createQueryParams(data);

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

	if (!response.ok) error(500, 'An unkown error occurred');

	return await response.json();
});

export const updateBookMetadata = form(editBookMetadataSchema, async (data): Promise<Book> => {
	const { locals } = getRequestEvent();

	const response = await locals.api.patch(`/books/${data.book_id}`, data);

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

	return await response.json();
});

export const updateBookCover = form(bookCoverUpload, async ({ book_id, file }) => {
	const { locals } = getRequestEvent();

	const formData = new FormData();
	formData.append('file', file);

	const response = await locals.api.putMultipart(`/books/${book_id}/cover`, formData);

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

	return await response.json();
});

export const uploadBooks = form(booksUpload, async ({ library_id, files }) => {
	const { locals } = getRequestEvent();

	const formData = new FormData();
	files.forEach((file) => {
		formData.append('files', file);
	});

	const response = await locals.api.postMultipart(
		`/books/fromFiles?library_id=${library_id}`,
		formData
	);

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

	return await response.json();
});

export const uploadBookFiles = form(bookFilesUpload, async ({ book_id, files }) => {
	const { locals } = getRequestEvent();

	const formData = new FormData();
	files.forEach((file) => {
		formData.append('files', file);
	});

	const response = await locals.api.postMultipart(`/books/${book_id}/files`, formData);

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

	return await response.json();
});

export const deleteBooks = command(deleteBooksSchema, async (data) => {
	const { locals } = getRequestEvent();

	const params = createQueryParams(data);

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

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

export const deleteBookFiles = command(deleteBookFilesSchema, async ({ book_id, ...data }) => {
	const { locals } = getRequestEvent();

	const params = createQueryParams(data);

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

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

export const updateBookProgress = command(
	updateBookProgressSchema,
	async ({ book_ids, ...data }) => {
		const { locals } = getRequestEvent();

		const params = createQueryParams({ book_ids: book_ids });

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

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

export const markBooksAsComplete = command(bookIdsSchema, async (data) => {
	const { locals } = getRequestEvent();

	const params = createQueryParams(data);

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

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