import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../core/contracts/server.dart';
import 'di_providers.dart';

class ServerListNotifier extends AsyncNotifier<List<EmbyServer>> {
  @override
  Future<List<EmbyServer>> build() async {
    final usecase = await ref.watch(listServersUseCaseProvider.future);
    return usecase.execute();
  }

  Future<void> refresh() async {
    state = const AsyncValue.loading();
    state = await AsyncValue.guard(() async {
      final usecase = await ref.read(listServersUseCaseProvider.future);
      return usecase.execute();
    });
  }

  Future<EmbyServer> save(EmbyServerSaveReq req) async {
    final usecase = await ref.read(saveServerUseCaseProvider.future);
    final server = await usecase.execute(req);
    await refresh();
    return server;
  }

  Future<void> delete(String id) async {
    final usecase = await ref.read(deleteServerUseCaseProvider.future);
    await usecase.execute(id);
    await refresh();
  }

  Future<EmbyServer> togglePause(String id) async {
    final usecase = await ref.read(togglePauseServerUseCaseProvider.future);
    final updated = await usecase.execute(id);
    await refresh();
    return updated;
  }

  Future<void> reorder(int oldIndex, int newIndex) async {
    final currentServers = state.value;
    if (currentServers == null || oldIndex == newIndex) return;

    final reorderedServers = List<EmbyServer>.of(currentServers);
    reorderedServers.insert(newIndex, reorderedServers.removeAt(oldIndex));

    state = AsyncValue.data(reorderedServers);
    try {
      final usecase = await ref.read(reorderServersUseCaseProvider.future);
      await usecase.execute(reorderedServers);
    } catch (_) {
      await refresh();
      rethrow;
    }
  }
}

final serverListProvider =
    AsyncNotifierProvider<ServerListNotifier, List<EmbyServer>>(
      ServerListNotifier.new,
    );
