<?php

use App\Livewire\Studio\Loyalty\Tier;
use App\Models\Tier as TierModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('renders successfully', function () {
    Livewire::test(Tier::class)
        ->assertViewIs('livewire.studio.loyalty.tiers')
        ->assertViewHas('pageTitle', 'Tier');
});

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

    $tier = TierModel::first();

    Livewire::test(Tier::class)->assertSee($tier->name);
});

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

    Livewire::test(Tier::class)
        ->set('form.name', $data['name'])
        ->set('form.min_points', $data['min_points'])
        ->set('form.max_points', $data['max_points'])
        ->call('create')
        ->assertHasNoErrors()
        ->assertDispatched('refreshDatatable');

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

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

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

    Livewire::test(Tier::class)
        ->call('openModal', 'update', 'Edit Tier', $tier->id)
        ->set('form.name', $data['name'])
        ->set('form.min_points', $data['min_points'])
        ->set('form.max_points', $data['max_points'])
        ->call('update')
        ->assertHasNoErrors()
        ->assertDispatched('refreshDatatable');

    $tier->refresh();

    expect($tier->name)->toBe($data['name']);
    expect($tier->min_points)->toBe($data['min_points']);
    expect($tier->max_points)->toBe($data['max_points']);
});

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

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

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