<?php

use App\Enums\Concentration;
use App\Livewire\Studio\Catalog\Perfume\Create;
use App\Models\Brand;
use App\Models\Category;
use App\Models\Outlet;
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 perfume']);
    Permission::firstOrCreate(['name' => 'create perfume']);
    $role->givePermissionTo(['view perfume', 'create perfume']);
    $this->user->assignRole($role);
});

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

it('shows validation errors when fields are empty', function () {
    Livewire::actingAs($this->user)
        ->test(Create::class)
        ->call('save')
        ->assertHasErrors([
            'form.name' => 'required',
            'form.sku' => 'required',
            'form.cost_price' => 'required', // Required for Owner
            'form.sale_price' => 'required',
            'form.category_ids' => 'required',
            'form.outlet_ids' => 'required',
        ]);
});

it('can store a new perfume', function () {
    $brand = Brand::factory()->create();
    $category = Category::factory()->create();
    $outlet = Outlet::factory()->create();

    Livewire::actingAs($this->user)
        ->test(Create::class)
        ->set('form.name', 'Perfume A')
        ->set('form.sku', 'SKU-Perfume-A')
        ->set('form.brand_id', $brand->id)
        ->set('form.cost_price', '50000')
        ->set('form.sale_price', '100000')
        ->set('form.concentration', Concentration::EAU_DE_PERFUME->value)
        ->set('form.category_ids', [$category->id])
        ->set('form.outlet_ids', [$outlet->id])
        ->call('save')
        ->assertHasNoErrors()
        ->assertRedirect(route('studio.catalog.perfume.index', ['notification' => 'Parfum berhasil ditambahkan.']));

    $this->assertDatabaseHas('perfumes', [
        'name' => 'Perfume A',
        'sku' => 'SKU-Perfume-A',
        'cost_price' => 50000,
        'sale_price' => 100000,
    ]);
});

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

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