<?php

declare(strict_types=1);

namespace App\Domain\Mail\Services;

use App\Domain\Sysapi\Contracts\SysapiBridge;
use App\Domain\Sysapi\Exceptions\SysapiException;

/**
 * Dovecot IMAP/POP3/LMTP sunucu işlemleri — sysapi köprüsü üzerinden.
 */
final class DovecotService
{
    public function __construct(private readonly SysapiBridge $sysapi) {}

    /**
     * DB ayarlarını /etc/dovecot/conf.d/onox-*.conf dosyaları olarak yazar.
     *
     * @param  array<int, array{key: string, value: string}>  $settings
     * @return array<string, mixed> {"files_written":[…],"checked":true,"count":N}
     *
     * @throws SysapiException
     */
    public function applyConfig(array $settings): array
    {
        $result = $this->sysapi->run('dovecot-conf-write', [
            'settings' => $settings,
        ], timeoutSeconds: 60);

        if ($result->failed()) {
            throw SysapiException::fromFailedResult('dovecot-conf-write', $result);
        }

        return $result->data ?? [];
    }

    /**
     * systemctl reload dovecot
     *
     * @return array<string, mixed> {"ok":true,"status":"active","uptime":"…"}
     *
     * @throws SysapiException
     */
    public function reload(): array
    {
        $result = $this->sysapi->run('dovecot-reload', [], timeoutSeconds: 30);

        if ($result->failed()) {
            throw SysapiException::fromFailedResult('dovecot-reload', $result);
        }

        return $result->data ?? [];
    }

    /**
     * systemctl restart dovecot
     *
     * @return array<string, mixed> {"ok":true,"status":"active","pid":N}
     *
     * @throws SysapiException
     */
    public function restart(): array
    {
        $result = $this->sysapi->run('dovecot-restart', [], timeoutSeconds: 30);

        if ($result->failed()) {
            throw SysapiException::fromFailedResult('dovecot-restart', $result);
        }

        return $result->data ?? [];
    }
}
