<?php

declare(strict_types=1);

namespace App\Services\Supplier\Channel;

use App\Services\Supplier\Dto\SupplierProjectDto;
use App\Services\Supplier\SupplierPortalClient;

/**
 * Ярус 1: тонкий адаптер над SupplierPortalClient (rt-project-* AJAX).
 *
 * Spec: docs/superpowers/specs/2026-05-19-supplier-project-channel-failover-design.md §4.2
 */
final class AjaxProjectChannel implements SupplierProjectChannel
{
    public function __construct(
        private readonly SupplierPortalClient $client,
    ) {}

    public function createProject(SupplierProjectDto $dto): int
    {
        return $this->client->saveProject($dto);
    }

    public function updateProject(int $externalId, SupplierProjectDto $dto): void
    {
        $this->client->updateProject($externalId, $dto);
    }

    /**
     * Сырые rt-строки портала → контрактная форма SupplierProjectChannel.
     *
     * Портал не отдаёт platform/signal_type/unique_key напрямую. Маппинг
     * (verified live 2026-05-19, см. SupplierPortalClient::listProjects docblock):
     *   - platform   ← префикс name "B<n>_..." (B1/B2/B3); иначе null;
     *   - signal_type ← type: hosts→site, calls→call, sms→sms;
     *   - unique_key ← content (домен / телефон / sender).
     * Сырые поля остаются (id, tag, name, type, content, ...) — для дебага.
     */
    public function listProjects(): array
    {
        $out = [];
        foreach ($this->client->listProjects() as $row) {
            if (! is_array($row)) {
                continue;
            }

            $name = (string) ($row['name'] ?? '');
            $platform = preg_match('/^(B[123])_/', $name, $m) === 1 ? $m[1] : null;

            $signalType = match ($row['type'] ?? null) {
                'hosts' => 'site',
                'calls' => 'call',
                'sms' => 'sms',
                default => null,
            };

            $out[] = $row + [
                'platform' => $platform,
                'signal_type' => $signalType,
                'unique_key' => (string) ($row['content'] ?? ''),
            ];
        }

        return $out;
    }
}
