<?php

use App\Models\User;
use Livewire\Livewire;
use Modules\Cms\Filament\Resources\CmsPages\Pages\CreateCmsPage;
use Modules\Cms\Filament\Resources\CmsPages\Pages\EditCmsPage;
use Modules\Cms\Filament\Resources\CmsPages\Pages\ListCmsPages;
use Modules\Cms\Models\CmsPage;
use Spatie\Permission\Models\Role;

use function Pest\Laravel\assertDatabaseHas;

beforeEach(function () {
    Role::findOrCreate('admin', 'web');

    $this->admin = User::factory()->create()->assignRole('admin');
    $this->actingAs($this->admin);
});

test('can list cms pages', function () {
    $pages = CmsPage::factory()->count(3)->create();

    Livewire::test(ListCmsPages::class)
        ->assertOk()
        ->assertCanSeeTableRecords($pages);
});

test('can create a cms page', function () {
    $page = CmsPage::factory()->make();

    Livewire::test(CreateCmsPage::class)
        ->fillForm([
            'page' => $page->page,
            'title' => $page->title,
            'mm_title' => $page->mm_title,
            'meta_tags' => $page->meta_tags,
            'meta_keywords' => $page->meta_keywords,
            'content' => $page->content,
            'mm_content' => $page->mm_content,
            'is_active' => true,
        ])
        ->call('create')
        ->assertNotified()
        ->assertRedirect();

    assertDatabaseHas(CmsPage::class, [
        'page' => $page->page,
        'title' => $page->title,
    ]);
});

test('can edit a cms page', function () {
    $page = CmsPage::factory()->create();

    Livewire::test(EditCmsPage::class, ['record' => $page->getRouteKey()])
        ->assertOk()
        ->fillForm(['title' => 'Updated Title'])
        ->call('save')
        ->assertNotified();

    assertDatabaseHas(CmsPage::class, [
        'id' => $page->id,
        'title' => 'Updated Title',
    ]);
});

test('requires a unique page slug', function () {
    CmsPage::factory()->create(['page' => 'miniapp_faq']);
    $page = CmsPage::factory()->make(['page' => 'miniapp_faq']);

    Livewire::test(CreateCmsPage::class)
        ->fillForm([
            'page' => $page->page,
            'title' => $page->title,
            'mm_title' => $page->mm_title,
        ])
        ->call('create')
        ->assertHasFormErrors(['page' => 'unique']);
});
