import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:kasy_kit/features/llm_chat/api/llm_chat_message_entity.dart';
import 'package:logger/logger.dart';

final llmChatApiProvider = Provider<LlmChatApi>(
  (ref) => LlmChatApi(client: FirebaseFirestore.instance),
);

class LlmChatApi {
  final FirebaseFirestore _client;
  final Logger _logger = Logger();

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

  CollectionReference<Map<String, dynamic>> _messagesRef(String userId) =>
      _client.collection('users').doc(userId).collection('llm_messages');

  /// Returns all messages for a user, ordered by creation time (oldest first).
  Future<List<LlmChatMessageEntity>> loadMessages(String userId) async {
    final snapshot = await _messagesRef(userId)
        .orderBy('createdAt', descending: false)
        .get();
    return snapshot.docs
        .map((doc) => LlmChatMessageEntity.fromFirestore(doc.id, doc.data()))
        .toList();
  }

  /// Persists a single message to Firestore.
  Future<void> saveMessage(
    String userId,
    LlmChatMessageEntity message,
  ) async {
    try {
      await _messagesRef(userId).add(message.toFirestore());
    } catch (e) {
      _logger.e('Failed to persist LLM message: $e');
    }
  }

  /// Deletes all stored messages for a user (clear history).
  Future<void> clearHistory(String userId) async {
    final snapshot = await _messagesRef(userId).get();
    final batch = _client.batch();
    for (final doc in snapshot.docs) {
      batch.delete(doc.reference);
    }
    await batch.commit();
  }
}
