<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Str;

class Blog extends Model
{
    use HasFactory;

    protected $table = 'blogs';

    protected $keyType = 'string';

    protected $fillable = [
        'author_id',
        'title',
        'header',
        'image_url',
        'content',
        'category_id',
        'read_count',
        'minute_read',
        'slug',
        'status',
    ];

    protected $casts = [
        'read_count' => 'integer',
        'minute_read' => 'integer',
        'status' => 'boolean',
    ];

    // Automatically set UUID for `id` when creating a new record
    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            if (empty($model->id)) {
                $model->id = (string) Str::uuid();
            }
            if (empty($model->slug)) {
                $model->slug = Str::slug($model->title);
            }
        });
    }

    /**
     * Get the category that owns the blog.
     */
    public function category(): BelongsTo
    {
        return $this->belongsTo(BlogCategory::class, 'category_id', 'id');
    }

    /**
     * Get the author that owns the blog.
     */
    public function author(): BelongsTo
    {
        return $this->belongsTo(User::class, 'author_id', 'id');
    }
}
