import { Injectable, Logger } from "@nestjs/common";
import { Cron, CronExpression } from "@nestjs/schedule";
import { ContainerLifecycleService } from "../container-lifecycle/container-lifecycle.service";

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

  constructor(private readonly containerLifecycle: ContainerLifecycleService) {}

  @Cron(CronExpression.EVERY_5_MINUTES)
  async reapIdleContainers(): Promise<void> {
    this.logger.log("Running idle container reap cycle...");
    try {
      const result = await this.containerLifecycle.reapIdle();
      if (result.stopped.length > 0) {
        this.logger.log(
          `Stopped ${String(result.stopped.length)} idle containers: ${result.stopped.join(", ")}`
        );
      } else {
        this.logger.debug("No idle containers to stop");
      }
    } catch (error) {
      this.logger.error(
        "Failed to reap idle containers",
        error instanceof Error ? error.stack : String(error)
      );
    }
  }
}
