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 password = String(formData.get('user[password]')).trim();
		const confirmPassword = String(formData.get('confirm_password')).trim();
		let token = String(formData.get('token'));
		const userID = String(formData.get('user_id'));

		// Some validations
		/** @type {string | Array<{field: string, key: string}> | Record<string, {key: string}>} */
		const fieldsError = [];
		if (password.length < 8) {
			fieldsError.push({ field: 'user.user', key: 'validation.password' });
		}
		if (confirmPassword !== password) {
			fieldsError.push({ field: 'user.user', key: 'validation.password_match' });
		}
		if (Object.keys(fieldsError).length > 0) {
			return fail(400, { errors: formatError(fieldsError) });
		}

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

		const res = await fetch(`${BASE_API_URI}/users/password/change/${userID}/`, 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/login?message=${response.message}`);
		throw redirect(302, `${base}/auth/login?message=${response.message}`);
	}
};
