import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Order } from '@/entities/order.entity';

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

  constructor(
    @InjectRepository(Order)
    private orderRepo: Repository<Order>,
  ) {}

  // 每天凌晨1点执行，将前一天已入住且离店日期为前一天的订单标记为已完成
  @Cron('0 1 * * *')
  async completeExpiredOrders() {
    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    const yesterdayStr = yesterday.toISOString().split('T')[0];

    const result = await this.orderRepo
      .createQueryBuilder()
      .update(Order)
      .set({ status: 'completed', checkoutAt: new Date() })
      .where('status = :status', { status: 'checked_in' })
      .andWhere('DATE(checkOutDate) = :date', { date: yesterdayStr })
      .execute();

    if (result.affected && result.affected > 0) {
      this.logger.log(
        `已自动完成 ${result.affected} 笔过期订单 (${yesterdayStr})`,
      );
    }
  }
}
