<?php

declare(strict_types=1);

namespace App\Livewire\Admin\Blog\Posts;

use App\Models\BlogPost;
use Illuminate\Support\Facades\Storage;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.admin', ['title' => 'Blog posts'])]
final class Index extends Component
{
    use WithPagination;

    #[Computed]
    public function posts()
    {
        return BlogPost::query()
            ->with(['category', 'tags'])
            ->latest()
            ->paginate(10);
    }

    public function delete(int $postId): void
    {
        $post = BlogPost::query()->findOrFail($postId);
        if ($post->cover_image) {
            Storage::disk('public')->delete($post->cover_image);
        }
        $post->tags()->detach();
        $post->delete();
        session()->flash('success', 'Post deleted.');
    }

    public function render()
    {
        return view('livewire.admin.blog.posts.index');
    }
}
