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

const apiBase = () => env.API_INTERNAL_URL || 'http://localhost:8080';

export const load: PageServerLoad = async ({ locals, fetch }) => {
	const res = await fetch(`${apiBase()}/api/users/me/notification-preferences`);
	const notificationPrefs = res.ok ? await res.json() : null;
	return { user: locals.user, notificationPrefs };
};

export const actions: Actions = {
	updateProfile: async ({ request, fetch }) => {
		const formData = await request.formData();
		const body = {
			firstName: formData.get('firstName')?.toString().trim() || undefined,
			lastName: formData.get('lastName')?.toString().trim() || undefined,
			birthDate: (formData.get('birthDate')?.toString() || undefined) as string | undefined,
			email: formData.get('email')?.toString().trim() || undefined,
			contact: formData.get('contact')?.toString().trim() || undefined
		};

		const api = createApiClient(fetch);
		const result = await api.PUT('/api/users/me', { body });

		if (!result.response.ok) {
			return fail(result.response.status, {
				updateError: getErrorMessage(extractErrorCode(result.error))
			});
		}

		return { updateSuccess: true };
	},

	changePassword: async ({ request, fetch }) => {
		const formData = await request.formData();
		const currentPassword = formData.get('currentPassword')?.toString() ?? '';
		const newPassword = formData.get('newPassword')?.toString() ?? '';
		const confirmPassword = formData.get('confirmPassword')?.toString() ?? '';

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

		const api = createApiClient(fetch);
		const result = await api.POST('/api/users/me/password', {
			body: { currentPassword, newPassword }
		});

		if (!result.response.ok) {
			return fail(result.response.status, {
				passwordError: getErrorMessage(extractErrorCode(result.error))
			});
		}

		return { passwordSuccess: true };
	},

	updateNotificationPrefs: async ({ request, fetch }) => {
		const formData = await request.formData();
		const body = {
			notifyOnReply: formData.has('notifyOnReply'),
			notifyOnMention: formData.has('notifyOnMention')
		};

		const res = await fetch(`${apiBase()}/api/users/me/notification-preferences`, {
			method: 'PUT',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify(body)
		});

		if (!res.ok) {
			const data = await res.json().catch(() => ({}));
			return fail(res.status, { prefsError: getErrorMessage(data?.code) });
		}

		return { prefsSuccess: true };
	}
};
