<?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');
});

// --- getserialnumber ---

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

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

it('stores serial data as value key when data is not an array', function () {
    Http::fake([
        '*/getserialnumber' => Http::response([
            'data' => 'SN-SCALAR',
            'metadata' => ['rowcount' => 1, 'issuccess' => true],
            'error' => null,
        ]),
    ]);

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

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

    $component = Livewire::test(Divers::class)
        ->call('getSerialNumber');

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

it('handles exception on getSerialNumber', function () {
    Http::fake([
        '*/getserialnumber' => function () {
            throw new \Illuminate\Http\Client\ConnectionException('Connection refused');
        },
    ]);

    $component = Livewire::test(Divers::class)
        ->call('getSerialNumber');

    expect($component->get('errorMessage'))->not->toBeNull();
    expect($component->get('serialData'))->toBe([]);
});

// --- codes_list ---

it('searches codes by exact code name', function () {
    Http::fake([
        '*/codes_list' => Http::response([
            'data' => [
                ['vala1' => 'CAS', 'vala2' => 'CASH', 'vala3' => '', 'vala4' => '', 'vala5' => '', 'vala6' => '', 'valn1' => 1, 'valn2' => 0],
                ['vala1' => 'VIR', 'vala2' => 'Virement', 'vala3' => '', 'vala4' => '', 'vala5' => '', 'vala6' => '', 'valn1' => 0, 'valn2' => 0],
            ],
            'metadata' => ['rowCount' => 2, 'source' => 'DBF'],
            'error' => null,
        ]),
    ]);

    Livewire::test(Divers::class)
        ->set('code', 'PAYMODE')
        ->call('searchCodes')
        ->assertSet('hasCodes', true)
        ->assertSet('codesData', [
            ['vala1' => 'CAS', 'vala2' => 'CASH', 'vala3' => '', 'vala4' => '', 'vala5' => '', 'vala6' => '', 'valn1' => 1, 'valn2' => 0],
            ['vala1' => 'VIR', 'vala2' => 'Virement', 'vala3' => '', 'vala4' => '', 'vala5' => '', 'vala6' => '', 'valn1' => 0, 'valn2' => 0],
        ]);

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

it('sends code parameter to API', function () {
    Http::fake([
        '*/codes_list' => Http::response([
            'data' => [],
            'metadata' => ['rowCount' => 0, 'source' => 'DBF'],
            'error' => null,
        ]),
    ]);

    Livewire::test(Divers::class)
        ->set('code', 'STOCK')
        ->call('searchCodes');

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

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('displays error message on codes_list 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');
});

it('sends select parameter to codes_list when filled', function () {
    Http::fake([
        '*/codes_list' => Http::response([
            'data' => [['vala1' => 'A', 'vala2' => '']],
            'metadata' => ['rowCount' => 1, 'source' => 'DBF'],
            'error' => null,
        ]),
    ]);

    Livewire::test(Divers::class)
        ->set('code', 'STOCK')
        ->set('codesSelect', 'vala1,vala2')
        ->call('searchCodes');

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

it('does not send select parameter to codes_list when empty', function () {
    Http::fake([
        '*/codes_list' => Http::response([
            'data' => [],
            'metadata' => ['rowCount' => 0, 'source' => 'DBF'],
            'error' => null,
        ]),
    ]);

    Livewire::test(Divers::class)
        ->set('code', 'STOCK')
        ->set('codesSelect', '')
        ->call('searchCodes');

    Http::assertSent(function ($request) {
        return str_contains($request->url(), 'codes_list')
            && ! array_key_exists('select', $request->data());
    });
});

it('handles exception on searchCodes', function () {
    Http::fake([
        '*/codes_list' => Http::response('Server Error', 500),
    ]);

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

    expect($component->get('errorMessage'))->not->toBeNull();
    expect($component->get('codesData'))->toBe([]);
});

// --- custom_geninv_updatestock ---

it('defaults stkMode to 1 (Restock)', function () {
    Livewire::test(Divers::class)
        ->assertSet('stkMode', '1');
});

it('calls custom_geninv_updatestock with all parameters in Restock mode', function () {
    Http::fake([
        '*/custom_geninv_updatestock' => Http::response([
            'data' => ['custom_geninv_updatestock' => 'OK : Change applied - Artid : 003R92572            - Real stock received (Restock mode) : 5.00'],
            'metadata' => ['rowcount' => 1, 'issuccess' => true],
            'error' => null,
        ]),
    ]);

    Livewire::test(Divers::class)
        ->set('mode', 'write')
        ->set('stkArtId', '003R92572')
        ->set('stkId', 'SG')
        ->set('stkQty', '5')
        ->set('stkMode', '1')
        ->set('stkThirdId', '0100002174')
        ->set('stkToCheck', '12.50')
        ->set('stkToCheckDetail', 'Test restock')
        ->call('updateStock')
        ->assertSet('hasUpdatedStock', true)
        ->assertSet('errorMessage', null);

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

        return str_contains($request->url(), 'custom_geninv_updatestock')
            && $body['ARTID'] === '003R92572'
            && $body['STKID'] === 'SG'
            && $body['QTY'] === '5'
            && $body['MODE'] === '1'
            && $body['THIRDID'] === '0100002174'
            && $body['TOCHECK'] === '12.50'
            && $body['TOCHECKDETAIL'] === 'Test restock';
    });
});

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

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

    Http::assertNothingSent();
});

it('shows validation error when THIRDID is missing in Restock mode', function () {
    Http::fake();

    Livewire::test(Divers::class)
        ->set('mode', 'write')
        ->set('stkArtId', '003R92572')
        ->set('stkId', 'SG')
        ->set('stkQty', '5')
        ->set('stkMode', '1')
        ->set('stkThirdId', '')
        ->call('updateStock')
        ->assertSet('hasUpdatedStock', false)
        ->assertSet('errorMessage', 'Le champ THIRDID est obligatoire en mode Restock (MODE=1).');

    Http::assertNothingSent();
});

it('does not require THIRDID in Inventory mode (MODE=0)', function () {
    Http::fake([
        '*/custom_geninv_updatestock' => Http::response([
            'data' => ['xml' => '<VFPData><headererror><errorcode>002</errorcode><description>Invalid parameter, inventory JNL not found for warehouse : SG</description></headererror></VFPData>'],
            'metadata' => ['rowcount' => 1, 'issuccess' => false],
            'error' => ['Code: 002, Description: Invalid parameter, inventory JNL not found for warehouse : SG'],
        ]),
    ]);

    Livewire::test(Divers::class)
        ->set('mode', 'write')
        ->set('stkArtId', '003R92572')
        ->set('stkId', 'SG')
        ->set('stkQty', '1')
        ->set('stkMode', '0')
        ->set('stkThirdId', '')
        ->call('updateStock')
        ->assertSet('hasUpdatedStock', true);

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

        return str_contains($request->url(), 'custom_geninv_updatestock')
            && $body['MODE'] === '0'
            && ! isset($body['THIRDID']);
    });
});

it('includes THIRDID in params only when filled', function () {
    Http::fake([
        '*/custom_geninv_updatestock' => Http::response([
            'data' => null,
            'metadata' => ['rowcount' => 0, 'issuccess' => false],
            'error' => 'Error',
        ]),
    ]);

    Livewire::test(Divers::class)
        ->set('mode', 'write')
        ->set('stkArtId', 'ART001')
        ->set('stkId', 'A')
        ->set('stkQty', '1')
        ->set('stkMode', '0')
        ->set('stkThirdId', '')
        ->call('updateStock');

    Http::assertSent(function ($request) {
        return ! array_key_exists('THIRDID', $request->data());
    });
});

it('always sends TOCHECK and TOCHECKDETAIL even when empty', function () {
    Http::fake([
        '*/custom_geninv_updatestock' => Http::response([
            'data' => ['custom_geninv_updatestock' => 'OK'],
            'metadata' => ['rowcount' => 1, 'issuccess' => true],
            'error' => null,
        ]),
    ]);

    Livewire::test(Divers::class)
        ->set('mode', 'write')
        ->set('stkArtId', 'ART001')
        ->set('stkId', 'SG')
        ->set('stkQty', '1')
        ->set('stkMode', '1')
        ->set('stkThirdId', 'THIRD001')
        ->set('stkToCheck', '')
        ->set('stkToCheckDetail', '')
        ->call('updateStock');

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

        return array_key_exists('TOCHECK', $body)
            && array_key_exists('TOCHECKDETAIL', $body)
            && $body['TOCHECK'] === ''
            && $body['TOCHECKDETAIL'] === '';
    });
});

it('handles API error on updateStock', function () {
    Http::fake([
        '*/custom_geninv_updatestock' => Http::response([
            'data' => ['xml' => '<VFPData><headererror><errorcode>002</errorcode><description>Invalid parameter</description></headererror></VFPData>'],
            'metadata' => ['rowcount' => 1, 'issuccess' => false],
            'error' => ['Code: 002, Description: Invalid parameter'],
        ]),
    ]);

    $component = Livewire::test(Divers::class)
        ->set('mode', 'write')
        ->set('stkArtId', 'ART001')
        ->set('stkId', 'SG')
        ->set('stkQty', '1')
        ->set('stkMode', '1')
        ->set('stkThirdId', 'THIRD001')
        ->call('updateStock');

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

it('handles exception on updateStock', function () {
    Http::fake([
        '*/custom_geninv_updatestock' => Http::response('Server Error', 500),
    ]);

    $component = Livewire::test(Divers::class)
        ->set('mode', 'write')
        ->set('stkArtId', 'ART001')
        ->set('stkId', 'SG')
        ->set('stkQty', '1')
        ->set('stkMode', '1')
        ->set('stkThirdId', 'THIRD001')
        ->call('updateStock');

    expect($component->get('errorMessage'))->not->toBeNull();
    expect($component->get('updateStockResult'))->toBe([]);
});
