<?php
namespace App\Models;

use App\Enums\ArticleStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class NewsArticle extends Model
{
    use HasFactory;
    protected $fillable = [
        'title', 'slug', 'excerpt', 'content', 'image',
        'category', 'author', 'published_at', 'status',
        'reading_time', 'featured',
        'seo_title', 'seo_description',
    ];

    protected function casts(): array
    {
        return [
            'status' => ArticleStatus::class,
            'featured' => 'boolean',
            'published_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (NewsArticle $article) {
            if (empty($article->slug)) {
                $article->slug = Str::slug($article->title);
            }
        });
    }

    public function gallery(): HasMany
    {
        return $this->hasMany(NewsGallery::class, 'news_article_id')->orderBy('sort_order');
    }

    public function scopePublished($query)
    {
        return $query->where('status', ArticleStatus::Published);
    }

    public function scopeFeatured($query)
    {
        return $query->where('featured', true)->published();
    }
}
