<?php

use App\Enums\OutletStatus;
use App\Livewire\Studio\Master\Outlet\Edit;
use Livewire\Livewire;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

beforeEach(function () {
    $this->setupUser();
    $this->outlet = $this->createFullOutlet(['name' => 'Original Outlet']);
    $this->user->outlets()->sync([$this->outlet->id]);

    $role = Role::firstOrCreate(['name' => 'Owner']);
    Permission::firstOrCreate(['name' => 'update outlet']);
    $role->givePermissionTo('update outlet');
    $this->user->assignRole($role);
});

it('renders the edit outlet page correctly', function () {
    $this->actingAs($this->user)
        ->get(route('studio.master.outlet.edit', $this->outlet))
        ->assertOk()
        ->assertSeeLivewire(Edit::class);
});

it('loads existing outlet data correctly', function () {
    Livewire::actingAs($this->user)
        ->test(Edit::class, ['outlet' => $this->outlet])
        ->assertSet('form.name', $this->outlet->name)
        ->assertSet('form.phone_number', $this->outlet->phone_number);
});

it('can update an outlet', function () {
    Livewire::actingAs($this->user)
        ->test(Edit::class, ['outlet' => $this->outlet])
        ->set('form.name', 'Outlet Diperbarui')
        ->set('form.phone_number', '0812 3456 7890')
        ->set('form.status', OutletStatus::UNDER_CONSTRUCTION->value)
        ->call('save')
        ->assertHasNoErrors()
        ->assertRedirect(route('studio.master.outlet.index', ['notification' => 'Outlet berhasil diperbarui.']));

    $this->assertDatabaseHas('outlets', [
        'id' => $this->outlet->id,
        'name' => 'Outlet Diperbarui',
        'status' => OutletStatus::UNDER_CONSTRUCTION->value,
    ]);
});

it('cannot update outlet without permission', function () {
    $this->user->roles()->detach();
    $this->user->permissions()->detach();

    Livewire::actingAs($this->user)
        ->test(Edit::class, ['outlet' => $this->outlet])
        ->set('form.name', 'Unauthorized Update')
        ->call('save')
        ->assertForbidden();
});
