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'

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

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

  @Cron(CronExpression.EVERY_DAY_AT_1AM)
  async handleExpiredVip() {
    const now = new Date()
    this.logger.log('Checking expired VIP/sprint memberships...')

    const expired = await this.userModel.find({
      plan: { $in: ['growth', 'sprint'] },
      $or: [
        { sprintExpireAt: { $lt: now } },
        { vipExpireAt: { $lt: now } },
      ],
    }).exec()

    if (expired.length === 0) {
      this.logger.log('No expired memberships found')
      return
    }

    const ids = expired.map(u => u._id)
    await this.userModel.updateMany(
      { _id: { $in: ids } },
      {
        $set: {
          plan: 'free',
          remaining: 3,
        },
        $unset: {
          vipExpireAt: '',
          sprintExpireAt: '',
          sprintRemaining: '',
        },
      },
    ).exec()

    this.logger.log(`Downgraded ${expired.length} expired memberships to free plan`)
  }
}
