<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Models\Project;
use App\Services\Supplier\SupplierPortalClient;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

/**
 * Синхронизирует Лидерра-проект с supplier_projects на B1/B2/B3
 * в зависимости от signal_type.
 *
 * Семантика:
 *   site / call  → B1 + B2 + B3
 *   sms с keyword → B2 + B3
 *   sms без keyword → B3
 *
 * Записывает полученные supplier_projects.id в projects.supplier_b{1,2,3}_project_id.
 *
 * Retry: 3 попытки с backoff [15s, 60s, 300s].
 *
 * Spec: docs/superpowers/plans/2026-05-11-plan5-frontend-projects-ui-plan.md Task 4
 */
class SyncSupplierProjectJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;

    /** @var array<int, int> */
    public array $backoff = [15, 60, 300];

    public function __construct(public int $projectId) {}

    public function handle(SupplierPortalClient $client): void
    {
        $project = Project::find($this->projectId);

        if ($project === null) {
            Log::warning("SyncSupplierProjectJob: project {$this->projectId} not found — skipping");

            return;
        }

        $platforms = $this->resolvePlatforms($project);

        foreach ($platforms as $platform) {
            $uniqueKey = $this->buildUniqueKey($project, $platform);
            $supplierProjectId = $client->ensureSupplierProject($platform, $project->signal_type, $uniqueKey);
            $column = 'supplier_'.strtolower($platform).'_project_id';
            $project->{$column} = $supplierProjectId;
        }

        $project->save();
    }

    /**
     * Возвращает список uppercase platform-кодов для данного project.
     * Коды соответствуют CHECK constraint: 'B1' / 'B2' / 'B3'.
     *
     * @return array<int, string>
     */
    private function resolvePlatforms(Project $project): array
    {
        if (in_array($project->signal_type, ['site', 'call'], true)) {
            return ['B1', 'B2', 'B3'];
        }

        if ($project->signal_type === 'sms') {
            return $project->sms_keyword ? ['B2', 'B3'] : ['B3'];
        }

        return [];
    }

    /**
     * Строит unique_key для пары (project, platform):
     *   site/call  → signal_identifier (домен / телефон)
     *   sms B2     → sender + '+' + keyword
     *   sms B3     → sender
     */
    private function buildUniqueKey(Project $project, string $platform): string
    {
        if (in_array($project->signal_type, ['site', 'call'], true)) {
            return (string) $project->signal_identifier;
        }

        // sms
        $sender = (string) ($project->sms_senders[0] ?? '');

        if ($platform === 'B2') {
            return $sender.'+'.($project->sms_keyword ?? '');
        }

        // B3
        return $sender;
    }
}
