import { fail, redirect } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { parseBackendError } from '$lib/shared/errors';
import type { Actions, PageServerLoad } from './$types';

interface InvitePrefill {
	firstName?: string;
	lastName?: string;
	email?: string;
}

export const load: PageServerLoad = async ({ url, fetch }) => {
	const code = url.searchParams.get('code');
	if (!code) {
		return { code: null, prefill: null, codeError: 'NO_INVITE_CODE' };
	}

	const apiUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
	const res = await fetch(`${apiUrl}/api/auth/invite/${encodeURIComponent(code)}`);

	if (!res.ok) {
		const backendError = await parseBackendError(res);
		return { code, prefill: null, codeError: backendError?.code ?? 'INTERNAL_ERROR' };
	}

	const prefill: InvitePrefill = await res.json();
	return { code, prefill, codeError: null };
};

export const actions = {
	default: async ({ request, fetch }) => {
		const formData = await request.formData();
		const code = formData.get('code') as string;
		const email = formData.get('email') as string;
		const password = formData.get('password') as string;
		const firstName = formData.get('firstName') as string;
		const lastName = formData.get('lastName') as string;
		const notifyOnMention = formData.get('notifyOnMention') === 'on';

		const apiUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
		const res = await fetch(`${apiUrl}/api/auth/register`, {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ code, email, password, firstName, lastName, notifyOnMention })
		});

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

		throw redirect(303, '/login?registered=1');
	}
} satisfies Actions;
