<?php

use App\Enums\OutletStatus;
use App\Livewire\Studio\Master\Outlet\Index;
use App\Models\Facility;
use App\Models\OpeningHour;
use App\Models\Outlet;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

beforeEach(function () {
    $this->user = User::factory()->create();
});

function createOutlet(array $attributes = [])
{
    return Outlet::factory()
        ->has(OpeningHour::factory()->count(7))
        ->has(Facility::factory()->count(5))
        ->state(fn () => array_merge([
            'status' => fake()->randomElement(OutletStatus::cases()),
        ], $attributes))
        ->create();
}

function mountIndexComponent(User $user)
{
    return Livewire::actingAs($user)->test(Index::class);
}

it('renders page successfully', function () {
    mountIndexComponent($this->user)
        ->assertViewIs('livewire.studio.master.outlet.index')
        ->assertViewHas('pageTitle', 'Outlet');
});

it('mounts outlets correctly', function () {
    $outlet = createOutlet();

    mountIndexComponent($this->user)
        ->assertSet('outlets.0.name', $outlet->name)
        ->assertSet('outlets.0.phone_number', $outlet->phone_number);
});

it('opens image modal when openImage is called', function () {
    $component = mountIndexComponent($this->user);

    $url = 'https://example.com/test.jpg';
    $component->call('openImage', $url)->assertSet('imageUrl', $url);
});

it('displays all outlets', function () {
    for ($i = 0; $i < 5; $i++) {
        createOutlet();
    }

    $outletCount = Outlet::count();
    $firstOutlet = Outlet::first();

    mountIndexComponent($this->user)
        ->assertSee($firstOutlet->name)
        ->assertViewHas('outlets', fn ($outlets) => count($outlets) === $outletCount);
});

it('deletes an outlet successfully', function () {
    $outlet = createOutlet();

    mountIndexComponent($this->user)
        ->call('delete', $outlet)
        ->assertHasNoErrors();

    $this->assertSoftDeleted('outlets', ['id' => $outlet->id]);
});
