<?php

namespace App\Service;

use Ovh\Api;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

/**
 * @codeCoverageIgnore Wrapper OVH API (SDK externe)
 */
class OvhService
{
    private ?Api $api = null;

    public function __construct(
        private LoggerInterface $logger,
        #[Autowire(env: 'OVH_KEY')] private string $appKey = '',
        #[Autowire(env: 'OVH_SECRET')] private string $appSecret = '',
        #[Autowire(env: 'OVH_CUSTOMER')] private string $consumerKey = '',
    ) {
    }

    public function isAvailable(): bool
    {
        return '' !== $this->appKey && '' !== $this->appSecret && '' !== $this->consumerKey;
    }

    /**
     * Liste tous les NDD du compte OVH.
     *
     * @return list<string>
     */
    public function listDomains(): array
    {
        if (!$this->isAvailable()) {
            return [];
        }

        try {
            return $this->getApi()->get('/domain');
        } catch (\Throwable $e) {
            $this->logger->error('OVH: erreur listDomains: '.$e->getMessage());

            return [];
        }
    }

    /**
     * Vérifie si un domaine est géré par notre compte OVH.
     */
    public function isDomainManaged(string $fqdn): bool
    {
        return \in_array($fqdn, $this->listDomains(), true);
    }

    /**
     * Récupère les infos d'un domaine OVH.
     *
     * @return array{domain: string, nameServerType: string, offer: string, transferLockStatus: string, whoisOwner: string}|null
     */
    public function getDomainInfo(string $fqdn): ?array
    {
        if (!$this->isAvailable()) {
            return null;
        }

        try {
            return $this->getApi()->get('/domain/'.$fqdn);
        } catch (\Throwable $e) {
            $this->logger->error('OVH: erreur getDomainInfo '.$fqdn.': '.$e->getMessage());

            return null;
        }
    }

    /**
     * Récupère les infos du service (expiration, création, statut).
     *
     * @return array{domain: string, expiration: string, creation: string, status: string, contactBilling: string, contactTech: string, contactAdmin: string}|null
     */
    public function getDomainServiceInfo(string $fqdn): ?array
    {
        if (!$this->isAvailable()) {
            return null;
        }

        try {
            return $this->getApi()->get('/domain/'.$fqdn.'/serviceInfos');
        } catch (\Throwable $e) {
            $this->logger->error('OVH: erreur getDomainServiceInfo '.$fqdn.': '.$e->getMessage());

            return null;
        }
    }

    /**
     * Récupère la zone DNS (OVH ou externe).
     *
     * @return array{name: string, hasDnsAnycast: bool, dnssecSupported: bool}|null
     */
    public function getZoneInfo(string $fqdn): ?array
    {
        if (!$this->isAvailable()) {
            return null;
        }

        try {
            return $this->getApi()->get('/domain/zone/'.$fqdn);
        } catch (\Throwable $e) {
            $this->logger->warning('OVH: zone non trouvee pour '.$fqdn);

            return null;
        }
    }

    private function getApi(): Api
    {
        if (null === $this->api) {
            $this->api = new Api(
                $this->appKey,
                $this->appSecret,
                'ovh-eu',
                $this->consumerKey,
            );
        }

        return $this->api;
    }
}
