<?php

use App\Livewire\Studio\Catalog\Brand;
use App\Models\Brand as BrandModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('renders successfully', function () {
    Livewire::test(Brand::class)
        ->assertViewIs('livewire.studio.catalog.brands')
        ->assertViewHas('pageTitle', 'Merek');
});

it('displays all brands', function () {
    BrandModel::factory()->count(10)->create();

    $brand = BrandModel::first();

    Livewire::test(Brand::class)->assertSee($brand->name);
});

it('can create a brand', function () {
    $data = BrandModel::factory()->raw();

    Livewire::test(Brand::class)
        ->call('openModal', 'create', 'Tambah Merek')
        ->set('form.name', $data['name'])
        ->set('form.slug', $data['slug'])
        ->set('form.sort_order', $data['sort_order'])
        ->call('create')
        ->assertHasNoErrors()
        ->assertDispatched('refreshDatatable');

    expect(BrandModel::count())->toBe(1);
    expect(BrandModel::first()->name)->toBe($data['name']);
});

it('can update a brand', function () {
    $brand = BrandModel::factory()->create();

    $data = BrandModel::factory()->raw();

    Livewire::test(Brand::class)
        ->call('openModal', 'update', 'Edit Merek', $brand->id)
        ->set('form.name', $data['name'])
        ->set('form.sort_order', $data['sort_order'])
        ->call('update')
        ->assertHasNoErrors()
        ->assertDispatched('refreshDatatable');

    $brand->refresh();

    expect($brand->name)->toBe($data['name']);
});

it('can delete an brand', function () {
    $brand = BrandModel::factory()->create();

    Livewire::test(Brand::class)
        ->call('delete', $brand)
        ->assertHasNoErrors()
        ->assertDispatched('refreshDatatable');

    expect(BrandModel::count())->toBe(0);
});
