<?php

declare(strict_types=1);

use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;

uses(DatabaseTransactions::class);

// Тумблер «Разблокировка смены источника» (флаг routing_match_by_snapshot) на экране
// «Интеграция с поставщиком» — чтобы владелец включал/выключал мышкой без правки БД.
// EnsureSaasAdmin — стаб в testing; actingAs нужен для прохода auth+admin middleware.

it('GET source-edit-flag returns false when flag absent', function (): void {
    $this->actingAs(User::factory()->create());
    DB::table('system_settings')->where('key', 'routing_match_by_snapshot')->delete();

    $this->getJson('/api/admin/supplier-integration/source-edit-flag')
        ->assertOk()
        ->assertJson(['enabled' => false]);
});

it('GET source-edit-flag returns true when flag set', function (): void {
    $this->actingAs(User::factory()->create());
    DB::table('system_settings')->updateOrInsert(
        ['key' => 'routing_match_by_snapshot'],
        ['value' => 'true', 'type' => 'bool', 'updated_at' => now()],
    );

    $this->getJson('/api/admin/supplier-integration/source-edit-flag')
        ->assertOk()
        ->assertJson(['enabled' => true]);
});

it('POST source-edit-flag enables the flag', function (): void {
    $this->actingAs(User::factory()->create());
    DB::table('system_settings')->where('key', 'routing_match_by_snapshot')->delete();

    $this->postJson('/api/admin/supplier-integration/source-edit-flag', ['enabled' => true])
        ->assertOk()
        ->assertJson(['enabled' => true]);

    expect(DB::table('system_settings')->where('key', 'routing_match_by_snapshot')->value('value'))
        ->toBe('true');
});

it('POST source-edit-flag disables the flag', function (): void {
    $this->actingAs(User::factory()->create());
    DB::table('system_settings')->updateOrInsert(
        ['key' => 'routing_match_by_snapshot'],
        ['value' => 'true', 'type' => 'bool', 'updated_at' => now()],
    );

    $this->postJson('/api/admin/supplier-integration/source-edit-flag', ['enabled' => false])
        ->assertOk()
        ->assertJson(['enabled' => false]);

    expect(DB::table('system_settings')->where('key', 'routing_match_by_snapshot')->value('value'))
        ->toBe('false');
});

it('POST source-edit-flag rejects non-boolean', function (): void {
    $this->actingAs(User::factory()->create());

    $this->postJson('/api/admin/supplier-integration/source-edit-flag', ['enabled' => 'maybe'])
        ->assertStatus(422);
});
