<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class ForumThread extends Model
{
    protected $fillable = [
        'forum_category_id', 'user_id', 'author_name', 'author_email',
        'title', 'slug', 'content', 'is_approved', 'is_pinned', 'is_locked', 'replies_count', 'last_reply_at',
    ];

    protected $casts = [
        'is_approved' => 'boolean',
        'is_pinned' => 'boolean',
        'is_locked' => 'boolean',
        'last_reply_at' => 'datetime',
    ];

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($thread) {
            if (empty($thread->slug)) {
                $thread->slug = Str::slug($thread->title).'-'.Str::random(6);
            }
        });
    }

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

    public function replies(): HasMany
    {
        return $this->hasMany(ForumReply::class, 'forum_thread_id')->orderBy('created_at');
    }

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

    public function scopeApproved($query)
    {
        return $query->where('is_approved', true);
    }

    public function syncReplyStats(): void
    {
        $last = $this->replies()->where('is_approved', true)->max('created_at');
        $this->update([
            'replies_count' => $this->replies()->where('is_approved', true)->count(),
            'last_reply_at' => $last ? \Illuminate\Support\Carbon::parse($last) : null,
        ]);
    }
}
