<?php

namespace App\Models;

use App\Enums\PostStatus;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'body',
        'status',
        'published_at',
    ];

    protected function casts(): array
    {
        return [
            'title' => 'array',
            'body' => 'array',
            'status' => PostStatus::class,
            'published_at' => 'datetime',
        ];
    }

    /**
     * Scope to filter published posts.
     */
    public function scopePublished($query)
    {
        return $query->where('status', PostStatus::Published);
    }

    /**
     * Scope to filter draft posts.
     */
    public function scopeDraft($query)
    {
        return $query->where('status', PostStatus::Draft);
    }

    /**
     * Get the title in the specified locale, with fallback to Arabic.
     */
    public function getTitle(?string $locale = null): string
    {
        $locale ??= app()->getLocale();

        return $this->title[$locale] ?? $this->title['ar'] ?? '';
    }

    /**
     * Get the body in the specified locale, with fallback to Arabic.
     */
    public function getBody(?string $locale = null): string
    {
        $locale ??= app()->getLocale();

        return $this->body[$locale] ?? $this->body['ar'] ?? '';
    }

    /**
     * Get the excerpt by stripping HTML and limiting to 150 characters.
     */
    public function getExcerpt(?string $locale = null): string
    {
        return Str::limit(strip_tags($this->getBody($locale)), 150);
    }
}
