<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class BlogPost extends Model
{
    protected $fillable = [
        'user_id', 'category_id', 'title', 'slug', 'excerpt', 'content',
        'featured_image', 'featured_image_alt', 'status', 'published_at',
        'views', 'seo_title', 'seo_description', 'seo_keywords', 'seo_schema',
    ];

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

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

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

    public function category(): BelongsTo
    {
        return $this->belongsTo(BlogCategory::class, 'category_id');
    }

    public function tags(): BelongsToMany
    {
        return $this->belongsToMany(BlogTag::class, 'blog_post_tag', 'post_id', 'tag_id');
    }

    public function scopePublished(Builder $q): Builder
    {
        return $q->where('status', 'published')
            ->where(function ($w) {
                $w->whereNull('published_at')->orWhere('published_at', '<=', now());
            });
    }

    public function url(): string
    {
        $slug = $this->category?->slug ?: BlogCategory::DEFAULT_SLUG;
        return url('blog/' . $slug . '/' . $this->slug);
    }

    public function featuredImageUrl(): ?string
    {
        return $this->featured_image
            ? url('uploads/blog/' . $this->featured_image)
            : null;
    }

    public static function generateSlug(string $title, ?int $excludeId = null): string
    {
        $base = str_replace(' ', '-', trim($title));
        $slug = $base;
        $counter = 1;

        while (
            static::where('slug', $slug)
                ->when($excludeId, fn($q) => $q->where('id', '!=', $excludeId))
                ->exists()
        ) {
            $slug = $base . '-' . $counter++;
        }

        return $slug;
    }
}
