import { Injectable, Logger } from '@nestjs/common'
import { Cron, CronExpression } from '@nestjs/schedule'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { User, UserDocument } from '../user/user.schema'
import { PricingService } from '../schemas/pricing.service'

@Injectable()
export class GravityTopUpService {
  private readonly logger = new Logger(GravityTopUpService.name)

  constructor(
    @InjectModel(User.name) private userModel: Model<UserDocument>,
    private pricingService: PricingService,
  ) {}

  @Cron(CronExpression.EVERY_DAY_AT_2AM)
  async topUpVipGravity() {
    this.logger.log('Topping up gravity for active VIP members...')
    const pricing = await this.pricingService.getConfig()
    const now = new Date()

    // 成长版 —— vipExpireAt 未过期
    const growthPlan = pricing.plans.growth
    const growthResult = await this.userModel.updateMany(
      {
        plan: 'growth',
        vipExpireAt: { $gt: now },
      },
      { $inc: { gravity: growthPlan.gravityPerMonth } },
    ).exec()
    if (growthResult.modifiedCount > 0) {
      this.logger.log(`Growth plan: topped up ${growthResult.modifiedCount} users with ${growthPlan.gravityPerMonth} gravity each`)
    }

    // 冲刺版 —— sprintExpireAt 未过期
    const sprintPlan = pricing.plans.sprint
    const sprintResult = await this.userModel.updateMany(
      {
        plan: 'sprint',
        sprintExpireAt: { $gt: now },
      },
      { $inc: { gravity: sprintPlan.gravityPerMonth } },
    ).exec()
    if (sprintResult.modifiedCount > 0) {
      this.logger.log(`Sprint plan: topped up ${sprintResult.modifiedCount} users with ${sprintPlan.gravityPerMonth} gravity each`)
    }
  }
}
