import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../data/models/user_profile_model.dart';
import '../../data/repositories/profile_repository.dart';

// 1. Repository Provider
final profileRepositoryProvider = Provider((ref) => ProfileRepository());

// 2. AsyncNotifier implementation (Modern Riverpod)
class ProfileNotifier extends AsyncNotifier<UserProfile?> {
  @override
  FutureOr<UserProfile?> build() async {
    // Initial data fetch
    return _fetch();
  }

  Future<UserProfile?> _fetch() async {
    return ref.read(profileRepositoryProvider).getMyProfile();
  }

  Future<UserProfile?> loadProfile() async {
    state = const AsyncValue.loading();
    final profile = await _fetch();
    state = AsyncValue.data(profile);
    return profile;
  }

  Future<void> updateProfile({
    required String name,
    required String phone,
    required String department,
  }) async {
    // Show loading state
    state = const AsyncValue.loading();
    
    // Perform update and then re-fetch profile
    state = await AsyncValue.guard(() async {
      await ref.read(profileRepositoryProvider).updateMyProfile(
        name: name,
        phone: phone,
        department: department,
      );
      return _fetch();
    });
  }
}

// 3. Provider definition
final profileProvider = AsyncNotifierProvider<ProfileNotifier, UserProfile?>(() {
  return ProfileNotifier();
});
