<?php

namespace App\Provisioning\Steps\Customer;

use App\Models\ProvisioningRun;
use App\Provisioning\StepResult;
use App\Services\Proxmox\ProxmoxClient;
use App\Support\NextcloudOcc;
use App\Support\ProvisioningSettings;

class ConfigureNextcloud extends CustomerStep
{
    public function __construct(private ProxmoxClient $pve) {}

    public function key(): string
    {
        return 'configure_nextcloud';
    }

    public function maxDuration(): int
    {
        return 300;
    }

    public function execute(ProvisioningRun $run): StepResult
    {
        $instance = $this->instance($run);
        $pve = $this->pve->forHost($instance->host);

        $fqdn = $instance->subdomain.'.'.ProvisioningSettings::dnsZone();

        // Idempotent occ calls (setting the same values is a no-op).
        $this->guest($pve, $run, NextcloudOcc::command('config:system:set trusted_domains 1 --value='.escapeshellarg($fqdn)));
        // Only a VERIFIED domain goes into trusted_domains. Nextcloud will
        // answer for anything listed here, so an unproven hostname added at
        // provisioning time would serve this customer's files to whoever
        // pointed that name at the proxy.
        //
        // And the other direction has to happen too. Writing the entry when
        // there is a domain and doing nothing when there is not leaves a
        // withdrawn domain trusted forever — the proof is gone, the router no
        // longer carries it, and Nextcloud would still answer to it the moment
        // anything reached it under that name. `config:system:delete` is the
        // occ command that removes the entry rather than blanking it, and it
        // exits 0 when the key is already absent, so the step stays idempotent
        // for the overwhelmingly common case of an instance that never had one.
        if ($instance->domainIsVerified()) {
            $this->guest($pve, $run, NextcloudOcc::command('config:system:set trusted_domains 2 --value='.escapeshellarg($instance->custom_domain)));
        } else {
            $this->guest($pve, $run, NextcloudOcc::command('config:system:delete trusted_domains 2'));
        }
        $this->guest($pve, $run, NextcloudOcc::command('background:cron'));
        $this->guest($pve, $run, NextcloudOcc::command('config:system:set default_phone_region --value=DE'));

        return StepResult::advance();
    }
}
