import 'dart:async';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_app/features/goods/products/domain/entities/category.dart';
import 'package:niogu_app/features/goods/products/domain/repositories/i_category_repository.dart';
import 'package:niogu_app/features/goods/products/presentation/providers/category_provider.dart';

class CategoryController extends AutoDisposeAsyncNotifier<void> {
  late final ICategoryRepository _categoryRepository;

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

  Future<void> addCategory(Category category) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _categoryRepository.addCategory(category);
    });

    state = result;

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

  Future<void> updateCategory(String id, String name, String? imagePath) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _categoryRepository.updateCategory(id, name, imagePath);
    });

    state = result;

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