<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Post extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'ulid', 'source_id', 'author_id', 'continent_id', 'country_id', 'category_id',
        'title', 'slug', 'excerpt', 'content', 'original_content', 'featured_image',
        'status', 'is_rewritten', 'is_featured', 'is_breaking',
        'source_url', 'source_name',
        'reading_time', 'views_count', 'comments_count', 'likes_count',
        'meta_title', 'meta_description', 'published_at',
    ];

    protected $casts = [
        'is_rewritten' => 'boolean',
        'is_featured'  => 'boolean',
        'is_breaking'  => 'boolean',
        'published_at' => 'datetime',
    ];

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($post) {
            $post->ulid = $post->ulid ?? (string) Str::ulid();
            $post->slug = $post->slug ?? Str::slug($post->title) . '-' . Str::lower(Str::random(5));
            $post->reading_time = max(1, (int) (str_word_count(strip_tags($post->content)) / 200));
        });
    }

    // ── Relationships ────────────────────────────────────────────────────────
    public function continent() { return $this->belongsTo(Continent::class); }
    public function country()   { return $this->belongsTo(Country::class); }
    public function category()  { return $this->belongsTo(Category::class); }
    public function source()    { return $this->belongsTo(Source::class); }
    public function author()    { return $this->belongsTo(User::class, 'author_id'); }
    public function tags()      { return $this->belongsToMany(Tag::class, 'post_tag'); }
    public function comments()  { return $this->hasMany(Comment::class); }
    public function views()     { return $this->hasMany(PostView::class); }
    public function likes()     { return $this->hasMany(PostLike::class); }
    public function bookmarks() { return $this->hasMany(Bookmark::class); }

    // ── Scopes ───────────────────────────────────────────────────────────────
    public function scopePublished($q)  { return $q->where('status', 'published')->whereNotNull('published_at'); }
    public function scopeFeatured($q)   { return $q->where('is_featured', true); }
    public function scopeBreaking($q)   { return $q->where('is_breaking', true); }
    public function scopeForContinent($q, $slug) { return $q->whereHas('continent', fn($c) => $c->where('slug', $slug)); }
    public function scopeForCountry($q, $slug)   { return $q->whereHas('country',   fn($c) => $c->where('slug', $slug)); }
    public function scopeForCategory($q, $slug)  { return $q->whereHas('category',  fn($c) => $c->where('slug', $slug)); }
}
