<?php

namespace App\Services\Traefik;

class FakeTraefikWriter implements TraefikWriter
{
    /** @var array<string, string> subdomain => backend */
    public array $routes = [];

    /** @var array<string, array<int, string>> subdomain => hostnames the router serves */
    public array $hostnames = [];

    /** @var array<string, string> subdomain => traffic host */
    public array $hosts = [];

    /** How many times a router file was written, so a test can prove a rewrite happened. */
    public int $writes = 0;

    public bool $certReady = true;

    /**
     * Hostnames that answer nothing however often they are probed — a
     * customer's own domain whose A record does not point at us. Consulted
     * before $certReady, so a test can have the platform address certified
     * while the custom domain is not.
     *
     * @var array<int, string>
     */
    public array $certUnreachable = [];

    public function write(string $trafficHost, string $subdomain, array $hostnames, string $backend): void
    {
        $this->routes[$subdomain] = $backend;
        $this->hostnames[$subdomain] = array_values($hostnames);
        $this->hosts[$subdomain] = $trafficHost;
        $this->writes++;
    }

    public function remove(string $trafficHost, string $subdomain): void
    {
        unset($this->routes[$subdomain], $this->hostnames[$subdomain], $this->hosts[$subdomain]);
    }

    public function certReachable(string $fqdn): bool
    {
        if (in_array($fqdn, $this->certUnreachable, true)) {
            return false;
        }

        return $this->certReady;
    }

    /** Does the router for this instance serve that hostname right now? */
    public function serves(string $subdomain, string $hostname): bool
    {
        return in_array($hostname, $this->hostnames[$subdomain] ?? [], true);
    }
}
