import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { TreePricingService } from '../../pricing/tree-pricing.service';

/**
 * 自动涨价定时任务
 *
 * 每小时检查一次是否到达自动涨价时间。
 * 涨价间隔以天为单位，小时级精度足够。
 * 涨价原因：总部运营成本压力。
 */
@Injectable()
export class AutoPriceIncreaseJob implements OnModuleInit {
  private readonly logger = new Logger(AutoPriceIncreaseJob.name);
  private isRunning = false;

  constructor(private readonly pricingService: TreePricingService) {}

  onModuleInit() {
    this.logger.log('AutoPriceIncreaseJob initialized');
  }

  @Cron('0 * * * *') // 每小时第0分钟执行
  async checkAndExecuteAutoIncrease(): Promise<void> {
    if (this.isRunning) {
      this.logger.warn('Auto price increase check already running, skipping...');
      return;
    }

    this.isRunning = true;
    try {
      const executed = await this.pricingService.executeAutoIncrease();
      if (executed) {
        this.logger.log('Auto price increase executed successfully');
      }
    } catch (error) {
      this.logger.error(`Auto price increase failed: ${error}`);
    } finally {
      this.isRunning = false;
    }
  }
}
