<?php

namespace App\Models;

use App\Traits\Auditable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Support\Str;

class BlogPost extends Model
{
    use HasFactory, Auditable;

    protected $fillable = [
        'title',
        'slug',
        'badge',
        'reading_time',
        'excerpt',
        'content',
        'featured_image_media_id',
        'sort_order',
        'is_featured',
        'is_published',
        'published_at',
        'seo_title',
        'seo_description',
    ];

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

    public function featuredImageMedia(): BelongsTo
    {
        return $this->belongsTo(Media::class, 'featured_image_media_id');
    }

    public function mediaUsages(): MorphMany
    {
        return $this->morphMany(MediaUsage::class, 'usable');
    }

    public function getImageUrlAttribute(): string
    {
        $media = $this->relationLoaded('featuredImageMedia')
            ? $this->featuredImageMedia
            : $this->featuredImageMedia()->first();

        if ($media) {
            return $media->url;
        }

        return asset('assets/themes/prespa-saas/assets/img/ps-patterns/hero-image.png');
    }

    public function getResolvedExcerptAttribute(): string
    {
        if (filled($this->excerpt)) {
            return (string) $this->excerpt;
        }

        return Str::limit(trim(strip_tags((string) $this->content)), 180);
    }

    public function getResolvedSeoTitleAttribute(): string
    {
        return $this->seo_title ?: $this->title;
    }

    public function getResolvedSeoDescriptionAttribute(): string
    {
        return $this->seo_description ?: $this->resolved_excerpt;
    }
}
