import 'package:supabase_flutter/supabase_flutter.dart' as supabase; import '../models/user_model.dart' as app; import '../../core/errors/failure.dart'; import '../../core/utils/unit_conversion_utils.dart'; class UserRepository { final supabase.SupabaseClient _client; UserRepository(this._client); Future getProfile(String userId) async { try { final response = await _client .from('users') .select() .eq('id', userId) .maybeSingle(); if (response != null) { return app.User.fromJson(response); } else { throw const ServerFailure('User profile not found'); } } catch (e) { throw _handleError(e); } } Future updateProfile({ required String userId, String? username, String? avatarUrl, String? bio, bool? isPublicProfile, String? twitterHandle, String? instagramHandle, String? tiktokHandle, String? websiteUrl, Gender? gender, DateTime? birthDate, double? heightCm, double? weightKg, HeightUnit heightUnit = HeightUnit.metric, WeightUnit weightUnit = WeightUnit.metric, }) async { try { final updates = {}; if (username != null) updates['username'] = username; if (avatarUrl != null) updates['avatar_url'] = avatarUrl; if (bio != null) updates['bio'] = bio; if (isPublicProfile != null) updates['is_public_profile'] = isPublicProfile; if (twitterHandle != null) updates['twitter_handle'] = twitterHandle; if (instagramHandle != null) updates['instagram_handle'] = instagramHandle; if (tiktokHandle != null) updates['tiktok_handle'] = tiktokHandle; if (websiteUrl != null) updates['website_url'] = websiteUrl; if (gender != null) updates['gender'] = gender.toDatabaseString(); if (birthDate != null) updates['birth_date'] = birthDate.toIso8601String().split('T').first; if (heightCm != null) updates['height_cm'] = heightCm; if (weightKg != null) updates['weight_kg'] = weightKg; updates['height_unit'] = heightUnit.code; updates['weight_unit'] = weightUnit.code; updates['updated_at'] = DateTime.now().toIso8601String(); final response = await _client .from('users') .update(updates) .eq('id', userId) .select(); if (response.isNotEmpty) { return app.User.fromJson(response.first); } else { throw const ServerFailure('Failed to update profile'); } } catch (e) { throw _handleError(e); } } Future isUsernameAvailable(String username) async { try { final response = await _client .from('users') .select('id') .eq('username', username) .maybeSingle(); return response == null; } catch (e) { throw _handleError(e); } } Future deleteAccount(String userId) async { try { await _client.from('users').delete().eq('id', userId); } catch (e) { throw _handleError(e); } } Failure _handleError(dynamic error) { if (error is supabase.PostgrestException) { if (error.code == '23505') { return const ValidationFailure('Username already taken'); } return ServerFailure(error.message); } return UnknownFailure(error.toString()); } }