import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/api/api_client.dart';
import '../../../core/api/api_paths.dart';
import '../../../core/api/guarded_api_call.dart';
import '../../auth/data/auth_providers.dart';
import '../domain/user_profile.dart';

final profileRepositoryProvider = Provider<ProfileRepository>((ref) {
  return ProfileRepository(ref.watch(apiClientProvider), ref);
});

class ProfileRepository {
  final ApiClient _apiClient;
  final Ref _ref;

  ProfileRepository(this._apiClient, this._ref);

  Future<UserProfile> getMe() async {
    final token = await _ref.read(authStateProvider.future);
    final data = await guardedApiCall(
      _ref,
      () => _apiClient.getJson(UserApiPaths.me, token: token),
    );
    return UserProfile.fromJson(data);
  }

  Future<UserProfile> updateMe({
    String? email,
    String? firstName,
    String? lastName,
  }) async {
    final token = await _ref.read(authStateProvider.future);
    final body = <String, dynamic>{
      if (email != null) 'email': email,
      if (firstName != null) 'firstName': firstName,
      if (lastName != null) 'lastName': lastName,
    };
    final data = await guardedApiCall(
      _ref,
      () => _apiClient.patchJson(UserApiPaths.me, body: body, token: token),
    );
    return UserProfile.fromJson(data);
  }
}