<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;

// ══════════════════════════════════════════════════════════════════
//  InPractice — ForumReply Model
//  Table: forum_replies
//
//  Updated to include:
//    - avg_rating + ratings_count (cached — never compute on read)
//    - ratings() relationship → ForumReplyRating
//    - getBadgeAttribute() — Field Advisor badge track
//      Thresholds: 3 = Helpful Voice, 10 = Trusted Advisor, 25 = Field Expert
// ══════════════════════════════════════════════════════════════════

class ForumReply extends Model
{
    use HasFactory;

    // ── Fillable ───────────────────────────────────────────────
    protected $fillable = [
        'forum_post_id',
        'user_id',
        'parent_reply_id',
        'body',
        'posted_as_nickname',
        'status',
        'is_best_answer',
        'like_count',
        'avg_rating',
        'ratings_count',
    ];

    // ── Casts ─────────────────────────────────────────────────
    protected $casts = [
        'posted_as_nickname' => 'boolean',
        'is_best_answer'     => 'boolean',
        'like_count'         => 'integer',
        'avg_rating'         => 'float',
        'ratings_count'      => 'integer',
    ];

    // ── Helpers ───────────────────────────────────────────────

    public function getAuthorNameAttribute(): string
    {
        if ($this->posted_as_nickname) {
            return $this->user->nickname;
        }
        return $this->user->show_real_name
            ? $this->user->name
            : $this->user->nickname;
    }

    public function isActive(): bool
    {
        return $this->status === 'active';
    }

    public function isTopLevel(): bool
    {
        return is_null($this->parent_reply_id);
    }

    // ── Field Advisor badge ────────────────────────────────────
    // Computed from user's highly_rated_replies_count (cached column).
    // Separate track from Case Practitioner badges.
    // Thresholds: 3 = Helpful Voice, 10 = Trusted Advisor, 25 = Field Expert

    public function getBadgeAttribute(): ?array
    {
        return self::resolveBadge($this->user->highly_rated_replies_count ?? 0);
    }

    public static function resolveBadge(int $count): ?array
    {
        if ($count >= 25) {
            return ['key' => 'field_expert',      'icon' => '🏆', 'min' => 25];
        }
        if ($count >= 10) {
            return ['key' => 'trusted_advisor',   'icon' => '⭐', 'min' => 10];
        }
        if ($count >= 3) {
            return ['key' => 'helpful_voice',     'icon' => '💬', 'min' => 3];
        }
        return null;
    }

    // ── Scopes ────────────────────────────────────────────────

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('status', 'active');
    }

    public function scopeTopLevel(Builder $query): Builder
    {
        return $query->whereNull('parent_reply_id');
    }

    public function scopeTopRated(Builder $query): Builder
    {
        return $query->orderByDesc('avg_rating')->orderByDesc('ratings_count');
    }

    // ── Relationships ─────────────────────────────────────────

    public function post(): BelongsTo
    {
        return $this->belongsTo(ForumPost::class, 'forum_post_id');
    }

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

    public function parent(): BelongsTo
    {
        return $this->belongsTo(ForumReply::class, 'parent_reply_id');
    }

    public function children(): HasMany
    {
        return $this->hasMany(ForumReply::class, 'parent_reply_id');
    }

    public function likes(): MorphMany
    {
        return $this->morphMany(ForumLike::class, 'likeable');
    }

    public function ratings(): HasMany
    {
        return $this->hasMany(ForumReplyRating::class, 'forum_reply_id');
    }
}