<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

/**
 * DiscussionTopic Model
 * 
 * Represents a topic category for organizing discussions.
 * Each topic can contain multiple discussions and provides
 * categorization for the discussion board.
 * 
 * @property int $id
 * @property string $name
 * @property string $slug
 * @property string|null $description
 * @property bool $is_active
 * @property int $sort_order
 * @property string|null $meta_title
 * @property string|null $meta_description
 * @property string|null $meta_keywords
 * @property string $icon
 * @property string $color
 * @property \Carbon\Carbon|null $created_at
 * @property \Carbon\Carbon|null $updated_at
 * @property \Carbon\Carbon|null $deleted_at
 */
class DiscussionTopic extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'slug',
        'description',
        'is_active',
        'sort_order',
        'meta_title',
        'meta_description',
        'meta_keywords',
        'icon',
        'color',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'is_active' => 'boolean',
        'sort_order' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    /**
     * The "booted" method of the model.
     * 
     * Automatically generate slug from name when creating.
     */
    protected static function booted(): void
    {
        static::creating(function (self $topic) {
            if (empty($topic->slug)) {
                $topic->slug = static::generateUniqueSlug($topic->name);
            }
        });

        static::updating(function (self $topic) {
            if ($topic->isDirty('name') && empty($topic->slug)) {
                $topic->slug = static::generateUniqueSlug($topic->name);
            }
        });
    }

    /**
     * Generate a unique slug for the topic.
     *
     * @param string $name
     * @return string
     */
    public static function generateUniqueSlug(string $name): string
    {
        $slug = Str::slug($name);
        $count = static::withTrashed()
            ->where('slug', 'like', "{$slug}%")
            ->count();

        return $count > 0 ? "{$slug}-{$count}" : $slug;
    }

    /**
     * Get all discussions in this topic.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function discussions(): HasMany
    {
        return $this->hasMany(Discussion::class, 'topic_id');
    }

    /**
     * Get active discussions in this topic.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function activeDiscussions(): HasMany
    {
        return $this->discussions()
            ->where('is_active', true)
            ->where('status', 'published');
    }

    /**
     * Get published discussions in this topic.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function publishedDiscussions(): HasMany
    {
        return $this->discussions()
            ->where('status', 'published')
            ->where('is_active', true);
    }

    /**
     * Scope a query to only include active topics.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope a query to order by sort order.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order')->orderBy('name');
    }

    /**
     * Get the count of discussions in this topic.
     *
     * @return int
     */
    public function getDiscussionsCountAttribute(): int
    {
        return $this->discussions()->count();
    }

    /**
     * Get the count of active discussions in this topic.
     *
     * @return int
     */
    public function getActiveDiscussionsCountAttribute(): int
    {
        return $this->activeDiscussions()->count();
    }

    /**
     * Get the URL for this topic.
     *
     * @return string
     */
    public function getUrlAttribute(): string
    {
        return route('public.discussions.topic', $this->slug);
    }

    /**
     * Get SEO-friendly meta title.
     *
     * @return string
     */
    public function getSeoTitleAttribute(): string
    {
        return $this->meta_title ?? $this->name . ' - Discussions';
    }

    /**
     * Get SEO-friendly meta description.
     *
     * @return string
     */
    public function getSeoDescriptionAttribute(): string
    {
        return $this->meta_description ?? Str::limit(strip_tags($this->description ?? ''), 160);
    }
}
