part of '../../daily_challenge_db.dart';

/// Created by Haoyi on 2023/10/11

extension AwardDatabase on DailyChallengeDB {
  Future<BatchData<AwardEntity>> loadAwards() async {
    final db = getDb();
    return await db.loadAwards();
  }

  updateAward(AwardEntity entity) async {
    final db = getDb();
    return await db.updateAward(entity);
  }
}

extension AwardDao on DatabaseExecutor {
  Future<BatchData<AwardEntity>> loadAwards() async {
    final result = await rawQuery("SELECT * FROM ${AwardEntity.tbName}");
    final batchResult = BatchData<AwardEntity>.empty();
    if (result.isEmpty) {
      return batchResult;
    }
    return batchResult..queryAll([for (var item in result) AwardEntity.fromMap(item)]);
  }

  Future<BatchData<AwardEntity>> updateAward(AwardEntity entity) async {
    final result = await insert(AwardEntity.tbName, entity.toMap(),
        conflictAlgorithm: ConflictAlgorithm.replace);
    final batchResult = BatchData<AwardEntity>.empty();

    if (result <= 0) {
      return batchResult;
    }
    return batchResult..insert(entity);
  }
}
