<?php

declare(strict_types=1);

use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;

/**
 * Тесты GET /api/lead-statuses — глобальный lookup статусов воронки.
 *
 * Таблица lead_statuses не tenant-aware, seeded в schema.sql:2130 (14 системных
 * статусов: new/viewed/worked/base/missed/negotiations/waiting_payment/
 * partnership/paid/closed/test_drive/hot/replacement/final_missed).
 */
uses(DatabaseTransactions::class);

test('GET /api/lead-statuses возвращает 200 и не пустой список', function () {
    $r = $this->getJson('/api/lead-statuses');

    $r->assertStatus(200);
    expect($r->json('lead_statuses'))->toBeArray();
    expect(count($r->json('lead_statuses')))->toBeGreaterThanOrEqual(14);
});

test('GET /api/lead-statuses возвращает все 14 системных статусов из seed', function () {
    $r = $this->getJson('/api/lead-statuses');

    $slugs = collect($r->json('lead_statuses'))->pluck('slug')->all();
    $expected = [
        'new', 'viewed', 'worked', 'base', 'missed', 'negotiations',
        'waiting_payment', 'partnership', 'paid', 'closed',
        'test_drive', 'hot', 'replacement', 'final_missed',
    ];
    foreach ($expected as $slug) {
        expect($slugs)->toContain($slug);
    }
});

test('GET /api/lead-statuses возвращает поля slug, name_ru, color_hex, sort_order, is_system', function () {
    $r = $this->getJson('/api/lead-statuses');

    $first = $r->json('lead_statuses.0');
    expect($first)->toHaveKeys(['slug', 'name_ru', 'is_system', 'sort_order', 'color_hex']);
    expect($first['slug'])->toBeString();
    expect($first['name_ru'])->toBeString();
    expect($first['is_system'])->toBeBool();
});

test('GET /api/lead-statuses сортирует по sort_order', function () {
    $r = $this->getJson('/api/lead-statuses');

    $sortOrders = collect($r->json('lead_statuses'))->pluck('sort_order')->all();
    $sorted = $sortOrders;
    sort($sorted);
    expect($sortOrders)->toBe($sorted);
});

test('GET /api/lead-statuses включает кастомный slug, добавленный после seed', function () {
    DB::table('lead_statuses')->insert([
        'slug' => 'custom_test_'.bin2hex(random_bytes(3)),
        'name_ru' => 'Кастомный тест',
        'is_system' => false,
        'sort_order' => 999,
        'color_hex' => '#ABCDEF',
    ]);

    $r = $this->getJson('/api/lead-statuses');

    $slugs = collect($r->json('lead_statuses'))->pluck('slug')->all();
    $custom = collect($slugs)->first(fn ($s) => str_starts_with($s, 'custom_test_'));
    expect($custom)->not->toBeNull();
});
