import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { getActiveAvatarUrl } from '$lib/server/storage';
import { handleAvatarUpload, handleAvatarRemoval, handleProfileUpdate } from '$lib/server/member-profile';

export const load: PageServerLoad = async ({ parent }) => {
	const { member } = await parent();

	// Resolve the correct avatar URL based on current storage settings
	if (member) {
		const activeAvatarUrl = await getActiveAvatarUrl(member);
		return {
			member: {
				...member,
				avatar_url: activeAvatarUrl
			}
		};
	}

	return { member };
};

export const actions: Actions = {
	updateProfile: async ({ request, locals }) => {
		const { member } = await locals.safeGetSession();

		if (!member) {
			return fail(401, { error: 'Not authenticated' });
		}

		const formData = await request.formData();
		const nationalityString = formData.get('nationality') as string;

		const result = await handleProfileUpdate(
			member.id,
			{
				first_name: formData.get('first_name') as string,
				last_name: formData.get('last_name') as string,
				phone: formData.get('phone') as string,
				address: formData.get('address') as string,
				nationality: nationalityString ? nationalityString.split(',').filter(Boolean) : []
			},
			{ useAdmin: true, requireAllFields: true }
		);

		if (!result.success) {
			return fail(400, { error: result.error });
		}

		return { success: 'Profile updated successfully!' };
	},

	uploadAvatar: async ({ request, locals }) => {
		const { member } = await locals.safeGetSession();

		if (!member) {
			return fail(401, { error: 'Not authenticated' });
		}

		const formData = await request.formData();
		const file = formData.get('avatar') as File;

		const result = await handleAvatarUpload(member, file, { useAdmin: true });

		if (!result.success) {
			return fail(400, { error: result.error });
		}

		return { success: result.successMessage };
	},

	removeAvatar: async ({ locals }) => {
		const { member } = await locals.safeGetSession();

		if (!member) {
			return fail(401, { error: 'Not authenticated' });
		}

		const result = await handleAvatarRemoval(member, { useAdmin: true });

		if (!result.success) {
			return fail(500, { error: result.error });
		}

		return { success: result.successMessage };
	}
};
