import { base } from '$app/paths';
import { BASE_API_URI } from '$lib/utils/constants';
import { formatError } from '$lib/utils/helpers';
import { fail, redirect } from '@sveltejs/kit';

/** @type {import('./$types').Actions} */
export const actions = {
	default: async ({ fetch, request }) => {
		const formData = await request.formData();
		const email = String(formData.get('email'));

		/** @type {RequestInit} */
		const requestInitOptions = {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({ email: email })
		};

		const res = await fetch(`${BASE_API_URI}/users/password/request-change/`, requestInitOptions);

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

		const response = await res.json();

		// redirect the user
		console.log('redirecting to: ', `${base}/auth/confirming?message=${response.message}`);
		throw redirect(302, `${base}/auth/confirming?message=${response.message}`);
	}
};
