import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { OrdersService } from './orders.service';

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

  constructor(private readonly ordersService: OrdersService) {}

  @Cron(process.env.THIRD_PARTY_ORDER_SYNC_CRON || '*/30 * * * *')
  async handleOrderSync() {
    if (process.env.THIRD_PARTY_ORDER_SYNC_CRON_ENABLED !== 'true') {
      return;
    }

    try {
      await this.ordersService.syncThirdPartyOrderListFromTask({
        page: process.env.THIRD_PARTY_ORDER_SYNC_PAGE,
        limit: process.env.THIRD_PARTY_ORDER_SYNC_LIMIT,
        recent: process.env.THIRD_PARTY_ORDER_SYNC_RECENT,
      });
    } catch (error) {
      this.logger.error(
        error instanceof Error ? error.message : String(error),
        error instanceof Error ? error.stack : undefined,
      );
    }
  }
}
