<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * Blog post model for the /blog section.
 *
 * @property int    $id
 * @property string $slug
 * @property string $title
 * @property string $body           HTML or Markdown content
 * @property string|null $excerpt
 * @property int|null $author_id
 * @property string|null $featured_image
 * @property string|null $meta_title
 * @property string|null $meta_description
 * @property bool   $is_published
 * @property \Carbon\Carbon|null $published_at
 */
class BlogPost extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'blog_posts';

    protected $fillable = [
        'slug',
        'title',
        'body',
        'excerpt',
        'author_id',
        'featured_image',
        'meta_title',
        'meta_description',
        'is_published',
        'published_at',
    ];

    protected $casts = [
        'is_published' => 'boolean',
        'published_at' => 'datetime',
    ];

    // ── Relations ────────────────────────────────────────────────────────

    public function author()
    {
        return $this->belongsTo(User::class, 'author_id');
    }

    // ── Scopes ───────────────────────────────────────────────────────────

    public function scopePublished($query)
    {
        return $query->where('is_published', true)
                     ->where(fn ($q) => $q->whereNull('published_at')->orWhere('published_at', '<=', now()));
    }

    // ── Accessors ────────────────────────────────────────────────────────

    public function getUrlAttribute(): string
    {
        return url('/blog/' . $this->slug);
    }
}
