<?php

use App\Livewire\Studio\Manage\Order\Index;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use Livewire\Livewire;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

beforeEach(function () {
    $this->setupUser();

    $role = Role::firstOrCreate(['name' => 'Owner']);
    $permissions = ['view order', 'delete order'];
    foreach ($permissions as $p) {
        Permission::firstOrCreate(['name' => $p]);
    }
    $role->syncPermissions($permissions);
    $this->user->assignRole($role);

    // Ensure user has an outlet
    $this->user->outlets()->sync([$this->outlet->id]);
});

it('renders the order index page', function () {
    $this->actingAs($this->user)
        ->get(route('studio.manage.order.index'))
        ->assertOk()
        ->assertSeeLivewire(Index::class);
});

it('can delete an order and restore outlet stock', function () {
    $product = Product::factory()->create();
    $order = Order::factory()->create([
        'outlet_id' => $this->outlet->id,
        'user_id' => $this->user->id,
        'total' => 100000,
    ]);

    $item = OrderItem::factory()->forProduct($product)->create([
        'order_id' => $order->id,
        'user_id' => $this->user->id,
        'quantity' => 2,
    ]);

    // Initial stock (after order was supposedly created)
    $this->outlet->products()->attach($product->id, ['stock' => 10]);

    Livewire::actingAs($this->user)
        ->test(Index::class)
        ->call('delete', $order->id)
        ->assertHasNoErrors();

    $this->assertSoftDeleted('orders', ['id' => $order->id]);

    // Check stock restored (10 + 2 = 12)
    $this->assertDatabaseHas('outlet_product', [
        'outlet_id' => $this->outlet->id,
        'product_id' => $product->id,
        'stock' => 12,
    ]);
});

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

    $this->actingAs($this->user)
        ->get(route('studio.manage.order.index'))
        ->assertForbidden();
});
