<?php

use App\Models\Company;
use App\Models\Transaction;
use App\Models\User;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Carbon;
use Livewire\Volt\Volt;

test('guests cannot access company transactions page', function () {
    $company = Company::factory()->create();

    $response = $this->get(route('company.transactions', ['company' => $company]));

    $response->assertRedirect(route('login'));
});

test('authenticated users can view company transactions page', function () {
    $this->actingAs(User::factory()->create());

    $company = Company::factory()->create();
    Transaction::factory()->count(2)->for($company)->create();

    $response = $this->get(route('company.transactions', ['company' => $company]));

    $response->assertOk();
});

test('company transactions component focuses on requested transaction and updates selection with filters', function () {
    $this->actingAs(User::factory()->create());

    $company = Company::factory()->create();
    $otherCompany = Company::factory()->create();

    $highRisk = Transaction::factory()->for($company)->requiresReview()->status(Transaction::STATUS_TRUE_POSITIVE)->create([
        'risk_score' => 92,
        'channel' => 'SWIFT',
        'executed_at' => Carbon::parse('2024-01-11 12:00:00'),
    ]);

    $suspect = Transaction::factory()->for($company)->requiresReview()->status(Transaction::STATUS_FALSE_POSITIVE)->create([
        'risk_score' => 61,
        'channel' => 'SEPA',
        'executed_at' => Carbon::parse('2024-01-10 10:30:00'),
    ]);

    Transaction::factory()->for($otherCompany)->requiresReview()->status(Transaction::STATUS_FALSE_POSITIVE)->create();

    $component = Volt::test('companies.transactions', [
        'company' => $company,
    ]);

    $component->set('selectedTransactionId', $suspect->id);

    expect($component->get('selectedTransactionId'))->toBe($suspect->id);

    $component->set('status', Transaction::STATUS_TRUE_POSITIVE);

    /** @var LengthAwarePaginator $transactions */
    $transactions = $component->get('transactions');

    expect($transactions->total())->toBe(1)
        ->and($transactions->items()[0]->id)->toBe($highRisk->id)
        ->and($component->get('selectedTransactionId'))->toBe($highRisk->id);

    $channels = $component->get('channelOptions');

    expect($channels)->toHaveKey('SEPA')
        ->toHaveKey('SWIFT')
        ->and($channels['all'])->toBe('Alle Kanäle');
});
