import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { CapabilityService } from '../services/capability.service';
import { RedisService } from '@/infrastructure/redis';

@Injectable()
export class CapabilityExpiryScheduler {
  private readonly logger = new Logger(CapabilityExpiryScheduler.name);
  private readonly LOCK_KEY = 'auth:capability:expiry:lock';

  constructor(
    private readonly capabilityService: CapabilityService,
    private readonly redis: RedisService,
  ) {}

  /**
   * 每 60 秒检查到期的临时限制并自动恢复
   */
  @Cron('*/60 * * * * *')
  async processExpiredRestrictions(): Promise<void> {
    const lockValue = await this.redis.acquireLock(this.LOCK_KEY, 55);
    if (!lockValue) return;

    try {
      const count = await this.capabilityService.processExpiredRestrictions();
      if (count > 0) {
        this.logger.log(`已恢复 ${count} 个到期的能力限制`);
      }
    } catch (error) {
      this.logger.error('处理到期限制失败', error);
    } finally {
      await this.redis.releaseLock(this.LOCK_KEY, lockValue);
    }
  }
}
