<?php

use App\Livewire\Studio\Loyalty\Customer;
use App\Models\Customer as CustomerModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

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

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

    $customer = CustomerModel::first();

    Livewire::test(Customer::class)->assertSee($customer->name);
});

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

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

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

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

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

    Livewire::test(Customer::class)
        ->call('openModal', 'update', 'Edit Customer', $customer->id)
        ->set('form.name', $data['name'])
        ->set('form.phone_number', $data['phone_number'])
        ->set('form.gender', $data['gender'])
        ->call('update')
        ->assertHasNoErrors()
        ->assertDispatched('refreshDatatable');

    $customer->refresh();

    expect($customer->name)->toBe($data['name']);
    expect($customer->phone_number)->toBe($data['phone_number']);
    expect($customer->gender)->toBe($data['gender']);
});

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

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

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