<?php

namespace App\Services\Monitoring;

class FakeMonitoringClient implements MonitoringClient
{
    /** @var array<string, string> id => url */
    public array $targets = [];

    /** Set to simulate the monitoring service being unreachable. */
    public ?string $failWith = null;

    public function registerTarget(string $name, string $url): string
    {
        if ($this->failWith !== null) {
            throw new \RuntimeException($this->failWith);
        }

        // Idempotent by URL — a retry after a crash returns the same target id.
        $existing = array_search($url, $this->targets, true);
        if ($existing !== false) {
            return $existing;
        }

        $id = 'mon-'.substr(sha1($url), 0, 12);
        $this->targets[$id] = $url;

        return $id;
    }

    public bool $healthy = true;

    public function deregisterTarget(string $externalId): void
    {
        unset($this->targets[$externalId]);
    }

    public function isHealthy(string $externalId): bool
    {
        return $this->health($externalId) ?? true;
    }

    public function health(string $externalId): ?bool
    {
        return $this->healthy;
    }
}
