import 'dart:async';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_app/features/profile/domain/entities/profile.dart';
import 'package:niogu_app/features/profile/domain/repositories/i_profile_repository.dart';
import 'package:niogu_app/features/profile/presentation/providers/profile_provider.dart';

class ProfileController extends AutoDisposeAsyncNotifier<void> {
  late final IProfileRepository _profileRepository;

  @override
  FutureOr<void> build() {
    _profileRepository = ref.read(profileRepositoryProvider);
  }

  Future<void> updateProfile(UpsertProfile profile) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _profileRepository.updateProfile(profile);
    });

    state = result;

    if (result is AsyncError) throw result.error!;
  }

  Future<void> updateBusinessInfo(BusinessInfo business) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _profileRepository.updateBusinessInfo(business);
    });

    state = result;

    if (result is AsyncError) throw result.error!;
  }

  Future<void> updatePassword(String newPassword) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _profileRepository.updatePassword(newPassword);
    });

    state = result;

    if (result is AsyncError) throw result.error!;
  }
}