// ============================================================
// AiAgentProvider — AI 智能助手 Riverpod Providers
// ============================================================

import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../../core/network/api_client.dart';

// ── 对话历史 ──────────────────────────────────────────────────

final chatHistoryProvider = FutureProvider.autoDispose((ref) async {
  final api = ApiClient.instance;
  final resp = await api.get('/api/v1/ai/sessions/current/messages');
  return resp.data['data'];
});

// ── 发送消息状态 ──────────────────────────────────────────────

class AiChatState {
  final List<Map<String, dynamic>> messages;
  final bool isSending;
  final String? error;

  const AiChatState({
    this.messages = const [],
    this.isSending = false,
    this.error,
  });

  AiChatState copyWith({
    List<Map<String, dynamic>>? messages,
    bool? isSending,
    String? error,
    bool clearError = false,
  }) {
    return AiChatState(
      messages: messages ?? this.messages,
      isSending: isSending ?? this.isSending,
      error: clearError ? null : (error ?? this.error),
    );
  }
}

class AiChatNotifier extends Notifier<AiChatState> {
  @override
  AiChatState build() => const AiChatState();

  Future<void> sendMessage(String content) async {
    state = state.copyWith(isSending: true, clearError: true);
    try {
      final api = ApiClient.instance;
      final resp = await api.post('/api/v1/ai/chat', data: {'message': content});
      final reply = resp.data['data'] as Map<String, dynamic>;
      state = state.copyWith(
        messages: [
          ...state.messages,
          {'role': 'user', 'content': content},
          {'role': 'assistant', 'content': reply['reply'] ?? reply['content'] ?? ''},
        ],
        isSending: false,
      );
    } catch (e) {
      state = state.copyWith(isSending: false, error: e.toString());
      rethrow;
    }
  }
}

final aiChatProvider = NotifierProvider<AiChatNotifier, AiChatState>(AiChatNotifier.new);
