import { BASE_API_URI } from '$lib/utils/constants';
import { formatError, userDatesFromRFC3339 } from '$lib/utils/helpers';
import { fail, redirect } from '@sveltejs/kit';
import { formDataToObject, processUserFormData } from '$lib/utils/processing';

/**
 * @typedef {Object} UpdateData
 * @property {Partial<App.Locals['user']>} user
 */

/** @type {import('./$types').PageServerLoad} */
export async function load({ locals, params }) {
	// redirect user if not logged in
	if (!locals.user) {
		throw redirect(302, `/auth/login?next=/auth/about/${params.id}`);
	}
}

/** @type {import('./$types').Actions} */
export const actions = {
	/**
	 *
	 * @param request - The request object
	 * @param fetch - Fetch object from sveltekit
	 * @param cookies - SvelteKit's cookie object
	 * @param locals - The local object, housing current user
	 * @returns Error data or redirects user to the home page or the previous page
	 */
	updateUser: async ({ request, fetch, cookies, locals }) => {
		let formData = await request.formData();

		const rawData = formDataToObject(formData);
		const processedData = processUserFormData(rawData);

		const isCreating = !processedData.user.id || processedData.user.id === 0;
		console.log('Is creating: ', isCreating);
		// console.dir(formData);
		console.dir(processedData.user.membership);
		const apiURL = `${BASE_API_URI}/backend/users/`;

		/** @type {RequestInit} */
		const requestUpdateOptions = {
			method: 'PATCH',
			credentials: 'include',
			headers: {
				'Content-Type': 'application/json',
				Cookie: `jwt=${cookies.get('jwt')}`
			},
			body: JSON.stringify(processedData)
		};
		const res = await fetch(apiURL, requestUpdateOptions);

		if (!res.ok) {
			const response = await res.json();
			const errors = formatError(response.errors);
			return fail(400, { errors: errors });
		}

		const response = await res.json();
		locals.user = response;
		userDatesFromRFC3339(locals.user);
		throw redirect(303, `/auth/about/${response.id}`);
	},

	/**
	 *
	 * @param request - The request object
	 * @param fetch - Fetch object from sveltekit
	 * @param cookies - SvelteKit's cookie object
	 * @param locals - The local object, housing current user
	 * @returns Error data or redirects user to the home page or the previous page
	 */
	uploadImage: async ({ request, fetch, cookies }) => {
		const formData = await request.formData();

		/** @type {RequestInit} */
		const requestInitOptions = {
			method: 'POST',
			headers: {
				Cookie: `jwt=${cookies.get('jwt')}`
			},
			body: formData
		};

		const res = await fetch(`${BASE_API_URI}/file/upload/`, requestInitOptions);

		if (!res.ok) {
			const response = await res.json();
			const errors = formatError(response.errors);
			return fail(400, { errors: errors });
		}

		const response = await res.json();

		return {
			success: true,
			profile_picture: response['']
		};
	},

	/**
	 *
	 * @param request - The request object
	 * @param fetch - Fetch object from sveltekit
	 * @param cookies - SvelteKit's cookie object
	 * @param locals - The local object, housing current user
	 * @returns Error data or redirects user to the home page or the previous page
	 */
	deleteImage: async ({ request, fetch, cookies }) => {
		const formData = await request.formData();

		/** @type {RequestInit} */
		const requestInitOptions = {
			method: 'DELETE',
			headers: {
				Cookie: `jwt=${cookies.get('jwt')}`
			},
			body: formData
		};

		const res = await fetch(`${BASE_API_URI}/file/delete/`, requestInitOptions);

		if (!res.ok) {
			const response = await res.json();
			const errors = formatError(response.errors);
			return fail(400, { errors: errors });
		}

		return {
			success: true,
			profile_picture: ''
		};
	}
};
