import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/api/api_client_provider.dart';
import '../../../core/auth/auth_notifier.dart';

class BestieHistoryItem {
  final String sessionId;
  final String? mitraId;
  final String mitraName;
  final DateTime? endedAt;
  final List<String> topics;
  final int sessionsCount;
  final bool mitraIsOnline;

  const BestieHistoryItem({
    required this.sessionId,
    required this.mitraId,
    required this.mitraName,
    required this.endedAt,
    required this.topics,
    required this.sessionsCount,
    required this.mitraIsOnline,
  });

  factory BestieHistoryItem.fromJson(Map<String, dynamic> json) {
    final endedAtRaw = json['ended_at'];
    return BestieHistoryItem(
      sessionId: json['id'] as String,
      mitraId: json['mitra_id'] as String?,
      mitraName: json['mitra_display_name'] as String? ?? 'Bestie',
      endedAt: endedAtRaw is String ? DateTime.tryParse(endedAtRaw)?.toLocal() : null,
      topics: (json['topics'] as List?)?.cast<String>() ?? const [],
      // sessions_count comes from PostgreSQL COUNT(*) which postgres.js
      // stringifies (bigint precision). Accept both shapes so the factory
      // doesn't crash when the backend forgets to ::int.
      sessionsCount: switch (json['sessions_count']) {
        num n => n.toInt(),
        String s => int.tryParse(s) ?? 1,
        _ => 1,
      },
      mitraIsOnline: json['mitra_is_online'] as bool? ?? false,
    );
  }
}

/// Scoped to the current customer so logging in as a different account (or
/// from anonymous → phone-verified) triggers a refetch instead of returning
/// the previous customer's cached list. Returns `[]` when no auth — keeps
/// SHome1st from issuing a doomed 401.
final bestieHistoryProvider =
    FutureProvider<List<BestieHistoryItem>>((ref) async {
  final customerId = ref.watch(authProvider.select((s) {
    final data = s.valueOrNull;
    return switch (data) {
      AuthAuthenticatedData d => d.profile['id'] as String?,
      AuthAnonymousData d => d.customerId,
      _ => null,
    };
  }));
  if (customerId == null) return const [];
  final api = ref.read(apiClientProvider);
  final response = await api.get('/api/client/chat/history');
  final items = (response['data']['items'] as List<dynamic>? ?? [])
      .cast<Map<String, dynamic>>();
  return items.map(BestieHistoryItem.fromJson).toList();
});

/// Cheap derived provider used by the home CTA to decide whether to show the
/// bestie-choice sheet or skip straight into the new-payment flow.
final bestieHistoryHasItemsProvider = FutureProvider<bool>((ref) async {
  final items = await ref.watch(bestieHistoryProvider.future);
  return items.isNotEmpty;
});
