<?php

use App\Livewire\Studio\Catalog\Bottle\Create;
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 bottle']);
    Permission::firstOrCreate(['name' => 'create bottle']);
    $role->givePermissionTo(['view bottle', 'create bottle']);
    $this->user->assignRole($role);
});

it('renders the bottle create page correctly', function () {
    $this->actingAs($this->user)
        ->get(route('studio.catalog.bottle.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.size' => 'required',
            'form.cost_price' => 'required',
            'form.sale_price' => 'required',
            'form.outlet_ids' => 'required',
        ]);
});

it('can store a new bottle', function () {
    $outlet = Outlet::factory()->create();

    Livewire::actingAs($this->user)
        ->test(Create::class)
        ->set('form.name', 'Bottle C')
        ->set('form.size', '100')
        ->set('form.cost_price', '5000')
        ->set('form.sale_price', '15000')
        ->set('form.outlet_ids', [$outlet->id])
        ->call('save')
        ->assertHasNoErrors()
        ->assertRedirect(route('studio.catalog.bottle.index', ['notification' => 'Botol berhasil ditambahkan.']));

    $this->assertDatabaseHas('bottles', [
        'name' => 'Bottle C',
        'size' => 100,
        'cost_price' => 5000,
        'sale_price' => 15000,
    ]);
});

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

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