import 'dart:convert';

import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../../../core/services/auth_proxy_service.dart';
import '../../../../core/services/auth_token_store.dart';
import '../../../../core/services/http_client.dart';
import '../../../../core/services/runtime_env.dart';
import '../models.dart';

class UserSessionsNotifier extends AsyncNotifier<List<UserSessionSummary>> {
  @override
  Future<List<UserSessionSummary>> build() async {
    return _fetchSessions();
  }

  Future<List<UserSessionSummary>> _fetchSessions() async {
    final baseUrl = runtimeBackendUrl();
    final url = Uri.parse('$baseUrl/api/v1/user/sessions');

    final useCookie = AuthTokenStore.usesCookie();
    final token = AuthTokenStore.getToken();

    final client = createHttpClient(withCredentials: useCookie);
    final headers = <String, String>{'Content-Type': 'application/json'};
    if (!useCookie && token != null) {
      headers['Authorization'] = 'Bearer $token';
    }

    try {
      final response = await client.get(url, headers: headers);
      if (response.statusCode != 200) {
        throw Exception('Failed to load sessions: ${response.statusCode}');
      }

      final body = jsonDecode(response.body) as Map<String, dynamic>;
      final items = (body['items'] as List?) ?? const [];
      return items
          .whereType<Map<String, dynamic>>()
          .map(UserSessionSummary.fromJson)
          .toList();
    } finally {
      client.close();
    }
  }

  Future<void> refresh() async {
    state = const AsyncLoading();
    state = await AsyncValue.guard(_fetchSessions);
  }

  Future<void> revokeSession(String sessionId) async {
    await AuthProxyService.revokeSession(sessionId);
    await refresh();
  }
}

final userSessionsProvider =
    AsyncNotifierProvider<UserSessionsNotifier, List<UserSessionSummary>>(() {
      return UserSessionsNotifier();
    });
