<?php

use App\Filament\Pages\Divers;
use App\Models\User;
use Illuminate\Support\Facades\Http;
use Livewire\Livewire;

beforeEach(function () {
    config([
        'logistics.base_url' => 'http://test-server.local',
        'logistics.api_key' => 'test-api-key',
        'logistics.folder' => 'testfolder',
        'logistics.timeout' => 30,
        'logistics.connect_timeout' => 10,
        'logistics.retry.times' => 1,
        'logistics.retry.sleep_ms' => 0,
    ]);

    $this->actingAs(User::factory()->create());
});

it('defaults to read mode', function () {
    Livewire::test(Divers::class)
        ->assertSet('mode', 'read');
});

it('can switch between read and write modes', function () {
    Livewire::test(Divers::class)
        ->set('mode', 'write')
        ->assertSet('mode', 'write')
        ->set('mode', 'read')
        ->assertSet('mode', 'read');
});

it('gets the serial number', function () {
    Http::fake([
        '*/getserialnumber' => Http::response([
            'data' => 'SN-12345',
            'metadata' => ['rowcount' => 1, 'issuccess' => true],
            'error' => null,
        ]),
    ]);

    Livewire::test(Divers::class)
        ->call('getSerialNumber')
        ->assertSet('hasSerial', true)
        ->assertSet('serialData', ['value' => 'SN-12345']);
});

it('searches codes by prefix', function () {
    Http::fake([
        '*/codes_list' => Http::response([
            'data' => [['code' => 'PAY01', 'vala1' => 'Comptant']],
            'metadata' => ['rowcount' => 1, 'issuccess' => true],
            'error' => null,
        ]),
    ]);

    Livewire::test(Divers::class)
        ->set('code', 'PAY')
        ->call('searchCodes')
        ->assertSet('hasCodes', true)
        ->assertSet('codesData', [['code' => 'PAY01', 'vala1' => 'Comptant']]);

    Http::assertSent(function ($request) {
        return str_contains($request->url(), 'codes_list')
            && $request->data()['code'] === 'PAY';
    });
});

it('shows validation error when code is empty', function () {
    Http::fake();

    Livewire::test(Divers::class)
        ->call('searchCodes')
        ->assertSet('hasCodes', false)
        ->assertSet('errorMessage', 'Le champ debut de code (code) est obligatoire.');

    Http::assertNothingSent();
});

it('calls custom_geninv_updatestock endpoint', function () {
    Http::fake([
        '*/custom_geninv_updatestock' => Http::response([
            'data' => null,
            'metadata' => ['rowcount' => 0, 'issuccess' => false],
            'error' => 'Unknown STKID',
        ]),
    ]);

    Livewire::test(Divers::class)
        ->set('mode', 'write')
        ->set('stkArtId', 'ART001')
        ->set('stkId', 'STK1')
        ->set('stkQty', '10')
        ->call('updateStock')
        ->assertSet('hasUpdatedStock', true);

    expect(true)->toBeTrue();

    Http::assertSent(function ($request) {
        $body = $request->data();

        return str_contains($request->url(), 'custom_geninv_updatestock')
            && $body['ARTID'] === 'ART001'
            && $body['STKID'] === 'STK1';
    });
});

it('shows validation error when updateStock required fields are empty', function () {
    Http::fake();

    Livewire::test(Divers::class)
        ->set('mode', 'write')
        ->call('updateStock')
        ->assertSet('hasUpdatedStock', false)
        ->assertSet('errorMessage', 'Les champs ARTID, STKID et QTY sont obligatoires.');

    Http::assertNothingSent();
});

it('displays error message on API failure', function () {
    Http::fake([
        '*/codes_list' => Http::response([
            'data' => null,
            'metadata' => ['rowcount' => 0, 'issuccess' => false],
            'error' => 'Invalid API key',
        ]),
    ]);

    $component = Livewire::test(Divers::class)
        ->set('code', 'TEST')
        ->call('searchCodes');

    expect($component->get('errorMessage'))->toContain('Invalid API key');
});
