<?php

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

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

it('shows validation error when fields are empty', function () {
    Livewire::actingAs($this->user)
        ->test(Create::class)
        ->set('form.type', '') // Set to empty to trigger required validation
        ->call('save')
        ->assertHasErrors([
            'form.name' => 'required',
            'form.code' => 'required',
            'form.type' => 'required',
            'form.discount_amount' => 'required',
            'form.tier_ids' => 'required',
            'form.outlet_ids' => 'required',
        ]);
});

it('validates unique voucher code', function () {
    Voucher::factory()->create(['code' => 'EXISTING']);

    Livewire::actingAs($this->user)
        ->test(Create::class)
        ->set('form.code', 'EXISTING')
        ->call('save')
        ->assertHasErrors(['form.code' => 'unique']);
});

it('can store a new voucher', function () {
    $outlet = Outlet::factory()->create();
    $tier = Tier::factory()->create(['min_spending' => 0]);

    Livewire::actingAs($this->user)
        ->test(Create::class)
        ->set('form.name', 'Promo Baru')
        ->set('form.code', 'PROMOBARU')
        ->set('form.tags', 'Promo')
        ->set('form.type', VoucherType::FIXED->value)
        ->set('form.discount_amount', '20.000')
        ->set('form.limit_per_user', '1')
        ->set('form.summary', 'Potongan harga 20rb')
        ->set('form.start_date', now()->addDay()->format('Y-m-d'))
        ->set('form.outlet_ids', [$outlet->id])
        ->set('form.tier_ids', [$tier->id])
        ->call('save')
        ->assertHasNoErrors()
        ->assertRedirect(route('studio.loyalty.voucher.index', [
            'notification' => 'Voucher berhasil ditambahkan.',
        ]));

    $this->assertDatabaseHas('vouchers', [
        'name' => 'Promo Baru',
        'code' => 'PROMOBARU',
        'discount_amount' => 20000,
    ]);
});

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

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