<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class News extends Model
{
    use HasFactory;

    protected $table = 'news';

    protected $fillable = [
        'author_id', 'title', 'slug', 'cover_image', 'excerpt', 'content',
        'category', 'tags', 'is_featured', 'is_published', 'published_at',
        'views', 'meta_title', 'meta_description',
    ];

    protected function casts(): array
    {
        return [
            'tags'         => 'array',
            'is_featured'  => 'boolean',
            'is_published' => 'boolean',
            'published_at' => 'datetime',
            'views'        => 'integer',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (News $n) {
            if (empty($n->slug)) {
                $n->slug = Str::slug($n->title) . '-' . Str::random(5);
            }
            if (empty($n->published_at) && $n->is_published) {
                $n->published_at = now();
            }
        });
    }

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

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

    public function coverImageUrl(): ?string
    {
        return $this->cover_image ? asset('storage/' . $this->cover_image) : null;
    }
}
