import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { createApiClient } from '$lib/shared/api.server';
import { parseBackendError } from '$lib/shared/errors';

export const load: PageServerLoad = async ({ url }) => {
	const token = url.searchParams.get('token');
	return { token };
};

export const actions = {
	default: async ({ request, fetch }) => {
		const formData = await request.formData();
		const token = formData.get('token') as string;
		const newPassword = formData.get('newPassword') as string;
		const confirmPassword = formData.get('confirmPassword') as string;

		if (newPassword !== confirmPassword) {
			return fail(400, { error: 'MISMATCH' });
		}

		const api = createApiClient(fetch);
		const result = await api.POST('/api/auth/reset-password', {
			body: { token, newPassword }
		});

		if (!result.response.ok) {
			const backendError = await parseBackendError(result.response);
			return fail(400, { error: backendError?.code ?? 'INTERNAL_ERROR' });
		}

		return { success: true };
	}
} satisfies Actions;
