import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logger/logger.dart';
import 'package:kasy_kit/core/data/api/http_client.dart';
import 'package:kasy_kit/features/llm_chat/api/llm_chat_message_entity.dart';

final llmChatApiProvider = Provider<LlmChatApi>(
  (ref) => LlmChatApi(client: ref.read(httpClientProvider)),
);

/// REST endpoints expected on your backend:
///   GET    /llm-messages            → List<LlmChatMessageEntity> (current user)
///   POST   /llm-messages            → saves one message
///   DELETE /llm-messages            → clears all messages (current user)
///
/// The server identifies the user via the Authorization: Bearer token
/// injected automatically by HttpClient.
class LlmChatApi {
  final HttpClient _client;
  final Logger _logger = Logger();

  LlmChatApi({required HttpClient client}) : _client = client;

  /// Returns all messages for the authenticated user, ordered oldest first.
  Future<List<LlmChatMessageEntity>> loadMessages(String userId) async {
    try {
      final response = await _client.get('/llm-messages');
      final list = response.data as List<dynamic>;
      return list
          .map((e) => LlmChatMessageEntity.fromJson(e as Map<String, dynamic>))
          .toList();
    } on DioException catch (e) {
      _logger.e('Failed to load LLM messages: $e');
      return [];
    }
  }

  /// Persists a single message via POST.
  Future<void> saveMessage(
    String userId,
    LlmChatMessageEntity message,
  ) async {
    try {
      await _client.post('/llm-messages', data: message.toJson());
    } catch (e) {
      _logger.e('Failed to persist LLM message: $e');
    }
  }

  /// Deletes all stored messages for the authenticated user.
  Future<void> clearHistory(String userId) async {
    try {
      await _client.delete('/llm-messages');
    } catch (e) {
      _logger.e('Failed to clear LLM history: $e');
    }
  }
}
