<?php

if (!defined('ABSPATH')) {
    exit;
}

final class SPP_Expiration_Service
{
    public function __construct(
        private SPP_Repository $repository,
        private SPP_Proxmox_Client $proxmox
    ) {
    }

    public function expire_due_deployments(): void
    {
        foreach ($this->repository->due_for_expiration() as $deployment) {
            $stop_error = null;

            if (!empty($deployment['proxmox_vm_id']) && $deployment['status'] !== 'STOPPED') {
                try {
                    $this->proxmox->stop_instance((string) ($deployment['provisioning_type'] ?? 'qemu'), (int) $deployment['proxmox_vm_id']);
                } catch (Throwable $error) {
                    $stop_error = $error->getMessage();
                }
            }

            $this->repository->mark_deployment_expired((int) $deployment['id'], $stop_error);
        }
    }
}
