<?php

use App\Livewire\Studio\Catalog\Category;
use App\Models\Category as CategoryModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

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

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

    $category = CategoryModel::first();

    Livewire::test(Category::class)->assertSee($category->name);
});

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

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

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

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

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

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

    $category->refresh();

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

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

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

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