import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { uploadAvatar, deleteAvatar, isS3Enabled, getActiveAvatarUrl } from '$lib/server/storage';
import { supabaseAdmin } from '$lib/server/supabase';

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 firstName = formData.get('first_name') as string;
		const lastName = formData.get('last_name') as string;
		const phone = formData.get('phone') as string;
		const address = formData.get('address') as string;
		const nationalityString = formData.get('nationality') as string;

		// Validation
		if (!firstName || firstName.length < 2) {
			return fail(400, { error: 'First name must be at least 2 characters' });
		}

		if (!lastName || lastName.length < 2) {
			return fail(400, { error: 'Last name must be at least 2 characters' });
		}

		if (!phone) {
			return fail(400, { error: 'Phone number is required' });
		}

		if (!address || address.length < 10) {
			return fail(400, { error: 'Please enter a complete address' });
		}

		const nationality = nationalityString ? nationalityString.split(',').filter(Boolean) : [];
		if (nationality.length === 0) {
			return fail(400, { error: 'Please select at least one nationality' });
		}

		// Update member profile (use admin client to bypass RLS)
		const { error } = await supabaseAdmin
			.from('members')
			.update({
				first_name: firstName,
				last_name: lastName,
				phone,
				address,
				nationality,
				updated_at: new Date().toISOString()
			})
			.eq('id', member.id);

		if (error) {
			console.error('Failed to update profile:', error);
			return fail(500, { error: 'Failed to update profile. Please try again.' });
		}

		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;

		if (!file || !file.size) {
			return fail(400, { error: 'Please select an image to upload' });
		}

		// First delete any existing avatar from both storage backends
		if (member.avatar_path) {
			await deleteAvatar(member.id, member.avatar_path);
		} else {
			await deleteAvatar(member.id);
		}

		// Upload the avatar to appropriate storage (or both)
		const result = await uploadAvatar(member.id, file);

		if (!result.success) {
			return fail(400, { error: result.error || 'Failed to upload avatar' });
		}

		// Determine active URL based on current S3 setting
		const s3Active = await isS3Enabled();
		const activeUrl = s3Active ? result.s3Url : result.localUrl;

		// Update member record with all avatar URLs (use admin client to bypass RLS)
		const { error: updateError } = await supabaseAdmin
			.from('members')
			.update({
				avatar_url: activeUrl || result.publicUrl,
				avatar_url_local: result.localUrl || null,
				avatar_url_s3: result.s3Url || null,
				avatar_path: result.path,
				updated_at: new Date().toISOString()
			})
			.eq('id', member.id);

		if (updateError) {
			console.error('Failed to update avatar URL:', updateError);
			return fail(500, { error: 'Failed to update profile with new avatar' });
		}

		return { success: 'Avatar uploaded successfully!' };
	},

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

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

		// Delete the avatar from BOTH storage backends using the stored path
		if (member.avatar_path) {
			await deleteAvatar(member.id, member.avatar_path);
		} else {
			// Fallback: try to delete common extensions
			await deleteAvatar(member.id);
		}

		// Update member record to clear all avatar URLs (use admin client to bypass RLS)
		const { error: updateError } = await supabaseAdmin
			.from('members')
			.update({
				avatar_url: null,
				avatar_url_local: null,
				avatar_url_s3: null,
				avatar_path: null,
				updated_at: new Date().toISOString()
			})
			.eq('id', member.id);

		if (updateError) {
			console.error('Failed to remove avatar URL:', updateError);
			return fail(500, { error: 'Failed to update profile' });
		}

		return { success: 'Avatar removed successfully!' };
	}
};
