<?php

declare(strict_types=1);

namespace App\Services\Supplier\Channel;

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

/**
 * Ярус 2: водит форму «Мои проекты» supplier-портала через manage-project.js.
 *
 * Spec: docs/superpowers/specs/2026-05-19-supplier-project-channel-failover-design.md §4.3
 */
final class FormProjectChannel implements SupplierProjectChannel
{
    public function __construct(
        private readonly PlaywrightBridge $bridge,
    ) {}

    public function createProject(SupplierProjectDto $dto): int
    {
        $out = $this->callBridge('create', null, $dto);
        $id = (int) ($out['external_id'] ?? 0);
        if ($id === 0) {
            throw new \RuntimeException('FormProjectChannel: create returned empty external_id');
        }

        return $id;
    }

    public function updateProject(int $externalId, SupplierProjectDto $dto): void
    {
        $out = $this->callBridge('update', $externalId, $dto);
        if (($out['ok'] ?? false) !== true) {
            throw new \RuntimeException('FormProjectChannel: update did not return ok=true');
        }
    }

    public function listProjects(): array
    {
        $out = $this->callBridge('list', null, null);

        return (array) ($out['projects'] ?? []);
    }

    /**
     * @return array<string, mixed>
     */
    private function callBridge(string $operation, ?int $externalId, ?SupplierProjectDto $dto): array
    {
        return $this->bridge->run([
            'script' => 'manage-project.js',
            'operation' => $operation,
            'externalId' => $externalId,
            'dto' => $dto !== null ? $this->mapDto($dto) : null,
            'login' => (string) config('services.supplier.login'),
            'password' => (string) config('services.supplier.password'),
            'url' => (string) config('services.supplier.portal_url'),
        ]);
    }

    /**
     * @return array<string, mixed>
     */
    private function mapDto(SupplierProjectDto $dto): array
    {
        return [
            'tag' => $dto->uniqueKey,
            'name' => $dto->uniqueKey,
            'platforms' => [$dto->platform],
            'signal_type' => $dto->signalType,
            'limit' => $dto->limit,
            'workdays' => $dto->workdays,
            'regions' => $dto->regions,
            'region_mode' => $dto->regionsReverse ? 'exclude' : 'include',
            'domains' => $dto->signalType === 'site' ? [$dto->uniqueKey] : [],
            'active' => $dto->status === 'active',
        ];
    }
}
