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

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

const _kTable = 'llm_messages';

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

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

  /// Returns all messages for a user, ordered by creation time (oldest first).
  Future<List<LlmChatMessageEntity>> loadMessages(String userId) async {
    final rows = await _client
        .from(_kTable)
        .select()
        .eq('user_id', userId)
        .order('created_at', ascending: true);
    return rows.map(LlmChatMessageEntity.fromJson).toList();
  }

  /// Persists a single message to Supabase.
  Future<void> saveMessage(
    String userId,
    LlmChatMessageEntity message,
  ) async {
    try {
      await _client.from(_kTable).insert({
        'user_id': userId,
        ...message.toJson(),
      });
    } 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 {
    await _client.from(_kTable).delete().eq('user_id', userId);
  }
}
