<?php

use App\Livewire\Studio\Loyalty\Voucher\Index;
use App\Models\Voucher;
use Livewire\Livewire;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

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

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

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

it('displays voucher statistics correctly', function () {
    Voucher::factory()->count(2)->create(['start_date' => now()->subDays(5)]);
    Voucher::factory()->create(['start_date' => now()->addDays(5)]);

    Livewire::actingAs($this->user)
        ->test(Index::class)
        ->assertSet('stats.0.value', 3) // Total
        ->assertSet('stats.1.value', 2) // Active (depends on implementation, assuming today is active)
        ->assertSet('stats.3.value', 1); // Upcoming
});

it('can delete a voucher', function () {
    $voucher = Voucher::factory()->create();

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

    $this->assertSoftDeleted('vouchers', [
        'id' => $voucher->id,
    ]);
});

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

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

it('cannot delete voucher without permission', function () {
    $this->user->roles()->detach();
    $this->user->permissions()->detach();

    $voucher = Voucher::factory()->create();

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