import 'package:dio/dio.dart';
import '../../../../core/network/api_endpoints.dart';

class KBRemoteDatasource {
  final Dio _dio;

  KBRemoteDatasource(this._dio);

  Future<List<String>> getKnowledgeBases() async {
    final response = await _dio.get(ApiEndpoints.ragKbs);
    final data = response.data as Map<String, dynamic>;
    return List<String>.from(data['knowledge_bases'] ?? []);
  }

  Future<String> uploadToKB({
    required String kbName,
    List<String>? urls,
    List<String>? filePaths,
    List<String>? fileNames,
    List<List<int>>? fileBytes,
  }) async {
    final formData = FormData();
    formData.fields.add(MapEntry('kb_name', kbName));

    if (urls != null && urls.isNotEmpty) {
      formData.fields.add(MapEntry('urls', urls.join(',')));
    }

    if (fileBytes != null && fileNames != null) {
      for (var i = 0; i < fileBytes.length; i++) {
        formData.files.add(MapEntry(
          'files',
          MultipartFile.fromBytes(
            fileBytes[i],
            filename: fileNames[i],
          ),
        ));
      }
    }

    final response = await _dio.post(
      ApiEndpoints.ragUpload,
      data: formData,
      options: Options(contentType: 'multipart/form-data'),
    );

    final data = response.data as Map<String, dynamic>;
    return data['message'] as String? ?? 'Upload complete';
  }
}