import supabase, { supaReady } from '@/components/supadb/aksupainstance.uts'
import type { UserProfile } from '@/types/mall-types.uts'

/**
 * 确保用户资料存在，如果不存在则创建基础资料
 * @param sessionUser 会话用户对象 (UTSJSONObject)
 * @returns 创建的用户资料，如果创建失败则返回 null
 */
export async function ensureUserProfile(sessionUser: UTSJSONObject): Promise<UserProfile | null> {
	try {
		await supaReady
        
		// 从 sessionUser 中获取用户ID和邮箱
		const userId = sessionUser.getString('id')
		const email = sessionUser.getString('email') ?? ''
		
		if (userId == null || userId === '') {
			console.error('无法获取用户ID')
			return null
		}
		
		// 检查用户是否已存在（ak_users 通过 auth_id 关联 auth.users.id）
		const checkRes = await supabase.from('ak_users')
			.select('*', {})
			.eq('auth_id', userId)
			.single()
			.execute()
		
		console.log('ensureUserProfile check ak_users:', {
			status: checkRes.status,
			hasData: checkRes.data != null,
			hasError: (checkRes as any).error != null,
			error: (checkRes as any).error
		})
		
		if (checkRes.status >= 200 && checkRes.status < 300 && checkRes.data != null) {
			// 用户已存在，返回现有资料（H5 下 checkRes.data 可能是 plain object，不一定是 UTSJSONObject）
			const existingUser = (typeof (checkRes.data as any).getString === 'function')
				? (checkRes.data as UTSJSONObject)
				: new UTSJSONObject(checkRes.data as any)
			return {
				id: existingUser.getString('id') ?? '',
				username: existingUser.getString('username') ?? '',
				email: existingUser.getString('email') ?? email,
				gender: existingUser.getString('gender'),
				birthday: existingUser.getString('birthday'),
				height_cm: existingUser.getNumber('height_cm'),
				weight_kg: existingUser.getNumber('weight_kg'),
				bio: existingUser.getString('bio'),
				avatar_url: existingUser.getString('avatar_url'),
				preferred_language: existingUser.getString('preferred_language'),
				role: existingUser.getString('role') ?? 'consumer',
				created_at: existingUser.getString('created_at'),
				updated_at: existingUser.getString('updated_at')
			} as UserProfile
		}
		
		// 用户不存在，创建新用户资料
		const newUserData = new UTSJSONObject()
		newUserData.set('id', userId)
		newUserData.set('email', email)
		newUserData.set('username', email.split('@')[0] ?? 'user') // 默认用户名为邮箱前缀
		
		const insertRes = await supabase.from('ak_users')
			.insert(newUserData)
			.select('*', {})
			.single()
			.execute()
		
		console.log('ensureUserProfile insert ak_users:', {
			status: insertRes.status,
			hasData: insertRes.data != null,
			hasError: (insertRes as any).error != null,
			error: (insertRes as any).error
		})
		
		if (insertRes.status >= 200 && insertRes.status < 300 && insertRes.data != null) {
			const newUser = (typeof (insertRes.data as any).getString === 'function')
				? (insertRes.data as UTSJSONObject)
				: new UTSJSONObject(insertRes.data as any)
			return {
				id: newUser.getString('id') ?? '',
				username: newUser.getString('username') ?? '',
				email: newUser.getString('email') ?? email,
				gender: newUser.getString('gender'),
				birthday: newUser.getString('birthday'),
				height_cm: newUser.getNumber('height_cm'),
				weight_kg: newUser.getNumber('weight_kg'),
				bio: newUser.getString('bio'),
				avatar_url: newUser.getString('avatar_url'),
				preferred_language: newUser.getString('preferred_language'),
				role: newUser.getString('role') ?? 'consumer',
				created_at: newUser.getString('created_at'),
				updated_at: newUser.getString('updated_at')
			} as UserProfile
		} else {
			console.error('创建用户资料失败:', insertRes.status)
			return null
		}
	} catch (error) {
		console.error('ensureUserProfile 异常:', error)
		return null
	}
}
