// - Add authentication check to ensure only admins can access this route.
// - Implement a load function to fetch a list of all users.
// - Create actions for updating user information (similar to the about/[id] route).

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

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

/** @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);

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

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

		const res = await fetch(apiURL, requestOptions);

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

		const response = await res.json();
		console.log('Server success response:', response);
		locals.user = response;
		userDatesFromRFC3339(locals.user);
		throw redirect(303, `/auth/admin/users`);
	},

	/**
	 *
	 * @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
	 */
	updateSubscription: async ({ request, fetch, cookies }) => {
		let formData = await request.formData();

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

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

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

		const res = await fetch(apiURL, requestOptions);

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

		const response = await res.json();
		console.log('Server success response:', response);
		throw redirect(303, `/auth/admin/users`);
	},

	/**
	 *
	 * @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
	 */
	userDelete: async ({ request, fetch, cookies }) => {
		let formData = await request.formData();

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

		const apiURL = `${BASE_API_URI}/backend/users`;

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

		const res = await fetch(apiURL, requestOptions);

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

		const response = await res.json();
		console.log('Server success response:', response);
		throw redirect(303, `/auth/admin/users`);
	},

	/**
	 *
	 * @param request - The request object
	 * @param fetch - Fetch object from sveltekit
	 * @param cookies - SvelteKit's cookie object
	 * @param locals - The local object, housing current subscription
	 * @returns
	 */
	subscriptionDelete: async ({ request, fetch, cookies }) => {
		let formData = await request.formData();

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

		const apiURL = `${BASE_API_URI}/backend/membership/subscriptions`;

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

		const res = await fetch(apiURL, requestOptions);

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

		const response = await res.json();
		console.log('Server success response:', response);
		throw redirect(303, `/auth/admin/users`);
	}
};
