<?php

use App\Enums\VoucherType;
use App\Livewire\Studio\Loyalty\Voucher\Edit;
use App\Models\Outlet;
use App\Models\Tier;
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' => 'update voucher']);
    $role->givePermissionTo(['update voucher']);
    $this->user->assignRole($role);
});

it('renders the voucher edit page correctly', function () {
    $voucher = Voucher::factory()->create();

    $this->actingAs($this->user)
        ->get(route('studio.loyalty.voucher.edit', ['voucher' => $voucher]))
        ->assertOk()
        ->assertSeeLivewire(Edit::class);
});

it('loads existing voucher data correctly', function () {
    $voucher = Voucher::factory()->create([
        'name' => 'Original Name',
        'code' => 'ORIGINAL',
        'type' => VoucherType::FIXED,
        'discount_amount' => 50000,
    ]);

    Livewire::actingAs($this->user)
        ->test(Edit::class, ['voucher' => $voucher])
        ->assertSet('form.name', 'Original Name')
        ->assertSet('form.code', 'ORIGINAL')
        ->assertSet('form.discount_amount', 50000);
});

it('can update a voucher', function () {
    $voucher = Voucher::factory()->create([
        'type' => VoucherType::FIXED,
        'start_date' => now()->addDays(2)->format('Y-m-d'),
    ]);
    $outlet = Outlet::factory()->create();
    $tier = Tier::factory()->create(['min_spending' => 0]);

    $voucher->outlets()->attach($outlet);
    $voucher->tiers()->attach($tier);

    Livewire::actingAs($this->user)
        ->test(Edit::class, ['voucher' => $voucher])
        ->set('form.name', 'Updated Name')
        ->set('form.discount_amount', '60.000')
        ->call('save')
        ->assertHasNoErrors()
        ->assertRedirect(route('studio.loyalty.voucher.index', [
            'notification' => 'Voucher berhasil diperbarui.',
        ]));

    $this->assertDatabaseHas('vouchers', [
        'id' => $voucher->id,
        'name' => 'Updated Name',
        'discount_amount' => 60000,
    ]);
});

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

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

    $this->actingAs($this->user)
        ->get(route('studio.loyalty.voucher.edit', ['voucher' => $voucher]))
        ->assertForbidden();
});
