import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../core/contracts/auth.dart';
import 'di_providers.dart';
import 'server_provider.dart';

class SessionNotifier extends AsyncNotifier<SessionListRes> {
  @override
  Future<SessionListRes> build() async {
    final usecase = await ref.watch(listSessionsUseCaseProvider.future);
    return usecase.execute();
  }

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

  Future<void> login({
    required String serverId,
    required String username,
    required String password,
  }) async {
    final usecase = await ref.read(authByNameUseCaseProvider.future);
    await usecase.execute(
      AuthByNameReq(serverId: serverId, username: username, password: password),
    );
    await refresh();
    ref.invalidate(serverListProvider);
  }

  Future<void> logout({String? serverId}) async {
    final usecase = await ref.read(logoutUseCaseProvider.future);
    await usecase.execute(serverId);
    await refresh();
  }

  Future<void> switchSession(String serverId) async {
    final usecase = await ref.read(switchSessionUseCaseProvider.future);
    await usecase.execute(serverId);
    await refresh();
  }
}

final sessionProvider = AsyncNotifierProvider<SessionNotifier, SessionListRes>(
  SessionNotifier.new,
);


final activeSessionProvider = Provider<AuthedSession?>((ref) {
  final state = ref.watch(sessionProvider);
  return state.maybeWhen(
    data: (data) {
      if (data.activeServerId == null) return null;
      for (final s in data.sessions) {
        if (s.isActive) return s;
      }
      return null;
    },
    orElse: () => null,
  );
});
