<?php

use App\Filament\Resources\WatchedEvents\Pages\CreateWatchedEvent;
use App\Filament\Resources\WatchedEvents\Pages\ListWatchedEvents;
use App\Models\User;
use App\Models\WatchedEvent;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

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

it('lists watched events', function () {
    $events = WatchedEvent::factory()->count(3)->create();

    Livewire::test(ListWatchedEvents::class)
        ->assertOk()
        ->assertCanSeeTableRecords($events);
});

it('creates a watched event from the form', function () {
    Livewire::test(CreateWatchedEvent::class)
        ->fillForm([
            'label' => 'Iran tensions Apr–May 2026',
            'starts_at' => '2026-04-01 00:00:00',
            'ends_at' => '2026-05-31 23:59:00',
            'notes' => 'Geopolitical event affecting Brent crude.',
        ])
        ->call('create')
        ->assertHasNoFormErrors();

    expect(WatchedEvent::where('label', 'Iran tensions Apr–May 2026')->exists())->toBeTrue();
});

it('validates ends_at is after starts_at', function () {
    Livewire::test(CreateWatchedEvent::class)
        ->fillForm([
            'label' => 'Bad dates',
            'starts_at' => '2026-05-01 00:00:00',
            'ends_at' => '2026-04-01 00:00:00',
        ])
        ->call('create')
        ->assertHasFormErrors(['ends_at']);
});

it('filters to currently active events', function () {
    $active = WatchedEvent::factory()->active()->create(['label' => 'Active event']);
    $inactive = WatchedEvent::factory()->inactive()->create(['label' => 'Inactive event']);

    Livewire::test(ListWatchedEvents::class)
        ->filterTable('currently_active')
        ->assertCanSeeTableRecords([$active])
        ->assertCanNotSeeTableRecords([$inactive]);
});
