import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/network/dio_client.dart';
import '../../data/datasources/kb_remote_datasource.dart';
import '../../data/repositories/kb_repository_impl.dart';
import 'kb_state.dart';

class KBCubit extends Cubit<KBState> {
  final KBRepositoryImpl _repo;

  KBCubit()
      : _repo = KBRepositoryImpl(KBRemoteDatasource(DioClient.instance)),
        super(const KBInitial());

  Future<void> loadKnowledgeBases() async {
    emit(const KBLoading());
    try {
      final kbs = await _repo.getKnowledgeBases();
      emit(KBLoaded(kbs));
    } catch (e) {
      emit(KBError(e.toString()));
    }
  }

  Future<void> upload({
    required String kbName,
    List<String>? urls,
    List<String>? fileNames,
    List<List<int>>? fileBytes,
  }) async {
    emit(const KBUploading());
    try {
      final message = await _repo.uploadToKB(
        kbName: kbName,
        urls: urls,
        fileNames: fileNames,
        fileBytes: fileBytes,
      );
      emit(KBUploadSuccess(message));
    } catch (e) {
      emit(KBUploadError(e.toString()));
    }
  }

  void resetToLoaded(List<String> kbs) {
    emit(KBLoaded(kbs));
  }
}