<?php

use App\Filament\Resources\ApiLogResource\Pages\ListApiLogs;
use App\Filament\Resources\ApiLogResource\Pages\ViewApiLog;
use App\Models\ApiLog;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

beforeEach(function () {
    $this->admin = User::factory()->admin()->create();
    $this->actingAs($this->admin);
});

it('renders the api log list page', function () {
    $logs = ApiLog::factory()->count(3)->create();

    Livewire::test(ListApiLogs::class)
        ->assertOk()
        ->assertCanSeeTableRecords($logs);
});

it('filters to errors only', function () {
    $ok = ApiLog::factory()->create(['status_code' => 200, 'error' => null]);
    $err = ApiLog::factory()->failed()->create();

    Livewire::test(ListApiLogs::class)
        ->filterTable('errors_only')
        ->assertCanSeeTableRecords([$err])
        ->assertCanNotSeeTableRecords([$ok]);
});

it('renders the view page for a log', function () {
    $log = ApiLog::factory()->create();

    Livewire::test(ViewApiLog::class, ['record' => $log->id])
        ->assertOk();
});

it('filters to errors only including null status codes', function () {
    $ok = ApiLog::factory()->create(['status_code' => 200, 'error' => null]);
    $err4xx = ApiLog::factory()->failed()->create(['status_code' => 429, 'error' => 'Too many requests']);
    $errNull = ApiLog::factory()->create(['status_code' => null, 'error' => 'Connection timeout']);

    Livewire::test(ListApiLogs::class)
        ->filterTable('errors_only')
        ->assertCanSeeTableRecords([$err4xx, $errNull])
        ->assertCanNotSeeTableRecords([$ok]);
});
