<?php
namespace Tests\Feature\Filament;

use App\Filament\Resources\StoreResource\Pages\CreateStore;
use App\Filament\Resources\StoreResource\Pages\EditStore;
use App\Filament\Resources\StoreResource\Pages\ListStores;
use App\Models\Province;
use App\Models\Store;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\TestCase;

class StoreResourceTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->actingAs(User::factory()->create());
    }

    public function test_can_list_stores(): void
    {
        Store::factory()->count(3)->create();

        Livewire::test(ListStores::class)
            ->assertCanSeeTableRecords(Store::all());
    }

    public function test_can_create_store(): void
    {
        Province::factory()->create(['code' => 'LUA', 'name' => 'Luanda']);

        Livewire::test(CreateStore::class)
            ->fillForm([
                'name' => 'Mangolê Teste',
                'slug' => 'mwangole-teste',
                'type' => 'hiper',
                'status' => 'open',
                'is_active' => true,
                'sort_order' => 1,
            ])
            ->call('create')
            ->assertHasNoFormErrors();

        $this->assertDatabaseHas('stores', [
            'name' => 'Mangolê Teste',
            'slug' => 'mwangole-teste',
        ]);
    }

    public function test_create_validation_requires_name(): void
    {
        Livewire::test(CreateStore::class)
            ->fillForm(['name' => ''])
            ->call('create')
            ->assertHasFormErrors(['name' => 'required']);
    }

    public function test_can_edit_store(): void
    {
        $store = Store::factory()->create();

        Livewire::test(EditStore::class, ['record' => $store->id])
            ->fillForm(['name' => 'Mangolê Editado'])
            ->call('save')
            ->assertHasNoFormErrors();

        $this->assertDatabaseHas('stores', [
            'id' => $store->id,
            'name' => 'Mangolê Editado',
        ]);
    }

    public function test_can_delete_store_via_bulk_action(): void
    {
        $store = Store::factory()->create();

        Livewire::test(ListStores::class)
            ->callTableBulkAction('delete', [$store->id])
            ->assertHasNoTableBulkActionErrors();

        $this->assertSoftDeleted($store);
    }
}
