<?php

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

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

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

    Livewire::actingAs($this->user)
        ->test(Create::class)
        ->set('form.name', 'Product B')
        ->set('form.sku', 'SKU-Product-B')
        ->set('form.cost_price', '20000')
        ->set('form.sale_price', '40000')
        ->set('form.outlet_ids', [$outlet->id])
        ->call('save')
        ->assertHasNoErrors()
        ->assertRedirect(route('studio.catalog.product.index', ['notification' => 'Produk berhasil ditambahkan.']));

    $this->assertDatabaseHas('products', [
        'name' => 'Product B',
        'sku' => 'SKU-Product-B',
        'cost_price' => 20000,
        'sale_price' => 40000,
    ]);
});

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

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