<?php

use App\Livewire\Studio\Master\Outlet\Index;
use App\Models\Outlet;
use Livewire\Livewire;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

beforeEach(function () {
    $this->setupUser();

    // Setup role and permission
    $role = Role::firstOrCreate(['name' => 'Owner']);
    Permission::firstOrCreate(['name' => 'view outlet']);
    Permission::firstOrCreate(['name' => 'delete outlet']);
    $role->givePermissionTo(['view outlet', 'delete outlet']);
    $this->user->assignRole($role);
});

it('renders the outlet index page correctly', function () {
    $this->actingAs($this->user)
        ->get(route('studio.master.outlet.index'))
        ->assertOk()
        ->assertSeeLivewire(Index::class);
});

it('displays list of outlets correctly', function () {
    $outlets = Outlet::factory()->count(3)->create();

    Livewire::actingAs($this->user)
        ->test(Index::class)
        ->assertViewHas('outlets', function ($viewOutlets) {
            return $viewOutlets->count() >= 3;
        })
        ->assertSee($outlets->first()->name)
        ->assertSee($outlets->last()->name);
});

it('can search outlets by name', function () {
    $targetOutlet = Outlet::factory()->create(['name' => 'Outlet Spesifik']);
    $otherOutlet = Outlet::factory()->create(['name' => 'Toko Biasa']);

    Livewire::actingAs($this->user)
        ->test(Index::class)
        ->set('search', 'Spesifik')
        ->assertSee($targetOutlet->name)
        ->assertDontSee($otherOutlet->name);
});

it('can filter outlets by status', function () {
    $operationalOutlet = Outlet::factory()->operational()->create(['name' => 'Outlet Aktif']);
    $terminatedOutlet = Outlet::factory()->terminated()->create(['name' => 'Outlet Tutup']);

    Livewire::actingAs($this->user)
        ->test(Index::class)
        ->set('status', [\App\Enums\OutletStatus::OPERATIONAL->value])
        ->assertSee($operationalOutlet->name)
        ->assertDontSee($terminatedOutlet->name);
});

it('can delete an outlet', function () {
    $outletToDelete = Outlet::factory()->create();

    Livewire::actingAs($this->user)
        ->test(Index::class)
        ->call('delete', $outletToDelete->id);

    $this->assertSoftDeleted('outlets', ['id' => $outletToDelete->id]);
});

it('cannot access index page without permission', function () {
    $this->user->roles()->detach();
    $this->user->permissions()->detach();

    $this->actingAs($this->user)
        ->get(route('studio.master.outlet.index'))
        ->assertForbidden();
});
