import 'dart:async';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_app/features/outlets/domain/entities/outlet.dart';
import 'package:niogu_app/features/outlets/domain/repositories/i_outlet_repository.dart';
import 'package:niogu_app/features/outlets/presentation/providers/outlet_provider.dart';

class OutletController extends AutoDisposeAsyncNotifier<void> {
  late final IOutletRepository _outletRepository;

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

  Future<void> saveStaffAdmin({
    required String outletId,
    UpsertStaffAdmin? firstStaffAdmin,
    UpsertStaffAdmin? secondStaffAdmin,
  }) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _outletRepository.saveStaffAdmin(
        outletId: outletId,
        firstStaffAdmin: firstStaffAdmin,
        secondStaffAdmin: secondStaffAdmin,
      );
    });

    state = result;

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

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

    final result = await AsyncValue.guard(() async {
      await _outletRepository.deleteStaffAdmin(userId);
    });

    state = result;

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

  Future<void> saveOutlet(UpsertOutlet upsertOutlet) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _outletRepository.saveOutlet(upsertOutlet);
    });

    state = result;

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

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

    final result = await AsyncValue.guard(() async {
      await _outletRepository.deleteOutlet(outletId);
    });

    state = result;

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