<?php

use App\Models\User;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Livewire\Livewire;
use Modules\Catalog\Filament\Resources\EvCompanies\Pages\CreateEvCompany;
use Modules\Catalog\Filament\Resources\EvCompanies\Pages\EditEvCompany;
use Modules\Catalog\Filament\Resources\EvCompanies\Pages\ListEvCompanies;
use Modules\Catalog\Models\EvCompany;
use Spatie\Permission\Models\Role;

use function Pest\Laravel\assertDatabaseHas;

beforeEach(function () {
    Role::findOrCreate('admin', 'web');

    $this->admin = User::factory()->create()->assignRole('admin');
    $this->actingAs($this->admin);
});

test('can list ev companies', function () {
    $companies = EvCompany::factory()->count(3)->create();

    Livewire::test(ListEvCompanies::class)
        ->assertOk()
        ->assertCanSeeTableRecords($companies);
});

test('renders the logo from the public disk in the table', function () {
    Storage::fake('public');
    Storage::disk('public')->put('logos/example.png', 'fake-image-contents');

    $company = EvCompany::factory()->create(['logo' => 'logos/example.png']);

    Livewire::test(ListEvCompanies::class)
        ->assertOk()
        ->assertSee(Storage::disk('public')->url($company->logo), escape: false);
});

test('can create an ev company', function () {
    $company = EvCompany::factory()->make();

    Livewire::test(CreateEvCompany::class)
        ->fillForm([
            'name' => $company->name,
            'mm_name' => $company->mm_name,
            'contact' => $company->contact,
            'address' => $company->address,
            'is_active' => true,
        ])
        ->call('create')
        ->assertNotified()
        ->assertRedirect();

    assertDatabaseHas(EvCompany::class, [
        'name' => $company->name,
        'slug' => Str::slug($company->name),
    ]);
});

test('can edit an ev company', function () {
    $company = EvCompany::factory()->create();

    Livewire::test(EditEvCompany::class, ['record' => $company->getRouteKey()])
        ->assertOk()
        ->fillForm(['name' => 'Updated Name'])
        ->call('save')
        ->assertNotified();

    assertDatabaseHas(EvCompany::class, [
        'id' => $company->id,
        'name' => 'Updated Name',
    ]);
});
