/**
 * Server-side load y actions para gestión de perfil de usuario
 */
import { fail, redirect } from '@sveltejs/kit';
import { authenticatedFetch } from '$lib/server/api';
import type { Actions, PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ cookies, fetch }) => {
	try {
		const response = await authenticatedFetch(
			'v1/core/users/me/profile',
			{
				method: 'GET',
			},
			cookies,
			fetch,
			'/login' // Redirigir a login si no está autenticado
		);

		if (!response.ok) {
			const errorData = await response.json().catch(() => ({}));
			return {
				profile: null,
				error: errorData.detail || 'Error al cargar el perfil'
			};
		}

		const profile = await response.json();
		return {
			profile,
			error: null
		};
	} catch (err: any) {
		console.error('Error loading profile:', err);
		return {
			profile: null,
			error: 'Error al cargar el perfil'
		};
	}
};

export const actions: Actions = {
	updateProfile: async ({ request, cookies, fetch }) => {
		const formData = await request.formData();		

		// Manejar subida de avatar si existe
		const avatarFile = formData.get('avatar') as File | null;
		let avatarUrl: string | null = null;


		if (avatarFile && avatarFile instanceof File && avatarFile.size > 0) {			
			try {
				const uploadFormData = new FormData();
				uploadFormData.append('file', avatarFile);
				
				const uploadResponse = await authenticatedFetch(
					'v1/core/users/me/avatar',
					{
						method: 'POST',
						body: uploadFormData
					},
					cookies,
					fetch,
					'/login'
				);

				if (uploadResponse.ok) {
					const result = await uploadResponse.json();
					avatarUrl = result.avatar_url;					
				} else {
					const errorText = await uploadResponse.text();
					console.error('Upload failed:', errorText);
				}
			} catch (err) {
				console.error('Error uploading avatar:', err);
			}
		}

		// Construir objeto de actualización desde FormData
		const updateData: Record<string, any> = {};
		
		for (const [key, value] of formData.entries()) {
			if (key === 'avatar') continue; // Skip avatar file
			if (value && value !== '') {
				updateData[key] = value;
			}
		}

		// Agregar avatar_url si se subió exitosamente
		if (avatarUrl) {
			updateData.avatar_url = avatarUrl;
		}

		try {
			const response = await authenticatedFetch(
				'v1/core/users/me/profile',
				{
					method: 'PUT',
					headers: {
						'Content-Type': 'application/json'
					},
					body: JSON.stringify(updateData)
				},
				cookies,
				fetch,
				'/login'
			);

			if (!response.ok) {
				const errorData = await response.json().catch(() => ({}));
				return fail(response.status, { 
					error: errorData.detail || 'Error al actualizar el perfil',
					values: updateData
				});
			}

			const updatedProfile = await response.json();
			return {
				success: true,
				profile: updatedProfile
			};
		} catch (err: any) {
			console.error('Error updating profile:', err);
			return fail(500, { 
				error: 'Error al actualizar el perfil',
				values: updateData
			});
		}
	}
};
