<?php

use App\Enums\ArticleStatus;
use App\Enums\CategoryType;
use App\Livewire\Studio\Manage\Article\Create;
use App\Models\Category;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Livewire\Livewire;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

beforeEach(function () {
    $this->setupUser();

    // Create necessary permissions
    $permissions = [
        'view article',
        'create article',
    ];

    foreach ($permissions as $permission) {
        Permission::firstOrCreate(['name' => $permission]);
    }

    $role = Role::create(['name' => 'Writer']);
    $role->givePermissionTo($permissions);
    $this->user->assignRole($role);
});

it('renders the article create page', function () {
    Livewire::actingAs($this->user)
        ->test(Create::class)
        ->assertStatus(200);
});

it('can store a new article', function () {
    Storage::fake('public');
    $category = Category::factory()->create(['type' => CategoryType::ARTICLE]);
    $image = UploadedFile::fake()->image('thumbnail.jpg');

    Livewire::actingAs($this->user)
        ->test(Create::class)
        ->set('form.title', 'Test Article')
        ->set('form.excerpt', 'This is a test excerpt')
        ->set('form.content', 'This is the content of the test article.')
        ->set('form.status', ArticleStatus::PUBLISHED->value)
        ->set('form.category_ids', [$category->id])
        ->set('form.thumbnail', [$image])
        ->call('save')
        ->assertRedirect(route('studio.manage.article.index', ['notification' => 'Artikel berhasil ditambahkan.']));

    $this->assertDatabaseHas('articles', [
        'title' => 'Test Article',
        'excerpt' => 'This is a test excerpt',
        'status' => ArticleStatus::PUBLISHED->value,
    ]);
});

it('validates article input', function () {
    Livewire::actingAs($this->user)
        ->test(Create::class)
        ->call('save')
        ->assertHasErrors(['form.title', 'form.content', 'form.thumbnail', 'form.category_ids']);
});
