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

/// Created by Haoyi on 2023/10/9

extension DailyChallengeDatabase on DailyChallengeDB {
  Future<BatchData<DailyChallengeEntity>> loadDailyChallengeByYM(int yearMonth) async {
    final db = getDb();
    return await db.loadDailyChallengeByYM(yearMonth);
  }

  Future<BatchData<DailyChallengeEntity>> updateDailyChallenge(DailyChallengeEntity entity) async {
    final db = getDb();
    return await db.updateDailyChallenge(entity);
  }
}

extension DailyChallengeDao on DatabaseExecutor {
  Future<BatchData<DailyChallengeEntity>> loadDailyChallengeByYM(int yearMonth) async {
    final result = await rawQuery(
        "SELECT * FROM ${DailyChallengeEntity.tbName} WHERE ${DailyChallengeEntity.dbYearMonth} = $yearMonth");
    final batchResult = BatchData<DailyChallengeEntity>.empty();
    if (result.isEmpty) {
      return batchResult;
    }
    return batchResult..queryAll([for (var item in result) DailyChallengeEntity.fromMap(item)]);
  }

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

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