<?php

namespace App\Models;

use App\Support\MediaUrl;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class BlogPost extends Model
{
    protected $fillable = [
        'title', 'slug', 'excerpt', 'content', 'cover_image',
        'focus_keyword', 'meta_title', 'meta_description', 'meta_keywords',
        'status', 'ai_generated', 'anime_id', 'linked_anime_ids', 'faq',
        'views', 'reading_time', 'published_at',
    ];

    protected $casts = [
        'linked_anime_ids' => 'array',
        'faq'              => 'array',
        'ai_generated'     => 'boolean',
        'published_at'     => 'datetime',
    ];

    public function getCoverUrlAttribute(): ?string
    {
        return MediaUrl::fromStoragePath($this->cover_image);
    }

    public function anime(): BelongsTo
    {
        return $this->belongsTo(Anime::class);
    }

    public function scopePublished($q)
    {
        return $q->where('status', 'published')->whereNotNull('published_at');
    }

    public function getReadableTimeAttribute(): string
    {
        return $this->reading_time . ' dk okuma';
    }

    public static function generateSlug(string $title): string
    {
        $slug = Str::slug($title, '-', 'tr');
        $base = $slug;
        $i = 1;
        while (static::where('slug', $slug)->exists()) {
            $slug = $base . '-' . $i++;
        }
        return $slug;
    }
}
