import { UserId, RestrictionCheckResult } from '@/domain/value-objects'
import { IPlantingRestrictionRepository } from '@/domain/repositories'

export interface IUserPlantingRecordRepository {
  countUserPlantingsInPeriod(userId: UserId, startAt: Date, endAt: Date): Promise<number>
}

export class PlantingRestrictionService {
  /**
   * 检查用户是否可以认种
   */
  async canUserPlant(
    userId: UserId,
    treeCount: number,
    restrictionRepository: IPlantingRestrictionRepository,
    userPlantingRepository: IUserPlantingRecordRepository,
  ): Promise<RestrictionCheckResult> {
    // 1. 检查账户限时限量
    const accountRestriction = await restrictionRepository.findActiveAccountRestriction()
    if (accountRestriction) {
      const userPlantingCount = await userPlantingRepository.countUserPlantingsInPeriod(
        userId,
        accountRestriction.startAt,
        accountRestriction.endAt,
      )

      if (userPlantingCount + treeCount > accountRestriction.accountLimitCount!) {
        return RestrictionCheckResult.blocked(
          `限制期内每个账户只能认种${accountRestriction.accountLimitCount}棵，` +
            `您已认种${userPlantingCount}棵`,
        )
      }
    }

    // 2. 检查总量限制
    const totalRestriction = await restrictionRepository.findActiveTotalRestriction()
    if (totalRestriction) {
      if (totalRestriction.currentTotalCount + treeCount > totalRestriction.totalLimitCount!) {
        return RestrictionCheckResult.blocked(
          `系统限制期内总认种量为${totalRestriction.totalLimitCount}棵，` +
            `当前已认种${totalRestriction.currentTotalCount}棵`,
        )
      }
    }

    return RestrictionCheckResult.allowed()
  }
}
