<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $guarded = [];

    protected $casts = [
        'published_at' => 'datetime',
        'gallery' => 'array',
    ];

    public function scopePublished(Builder $query): Builder
    {
        return $query->whereNotNull('published_at')->where('published_at', '<=', now());
    }

    /** draft | scheduled | published */
    public function status(): string
    {
        if (! $this->published_at) {
            return 'draft';
        }

        return $this->published_at->isFuture() ? 'scheduled' : 'published';
    }

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

    public function metaDescription(): string
    {
        return $this->meta_description ?: (string) $this->excerpt;
    }

    /** RichEditor stores HTML; the legacy/seeded posts use a markdown-lite syntax. */
    public function bodyIsHtml(): bool
    {
        return (bool) preg_match('/<(p|h[1-6]|ul|ol|blockquote|div|figure|img|br)[\s>\/]/i', (string) $this->body);
    }

    /** @return array<int, string> absolute URLs for gallery images */
    public function galleryUrls(): array
    {
        return collect($this->gallery ?? [])
            ->map(fn ($path) => \Illuminate\Support\Str::startsWith($path, ['http', 'images/'])
                ? asset($path)
                : asset('storage/'.$path))
            ->all();
    }

    public function coverUrl(): string
    {
        if (! $this->cover_path) {
            return asset('images/photo-bulb.jpg');
        }

        return \Illuminate\Support\Str::startsWith($this->cover_path, 'images/')
            ? asset($this->cover_path)
            : asset('storage/'.$this->cover_path);
    }

    public function getRouteKeyName(): string
    {
        return 'slug';
    }
}
