<?php

namespace App\Models;

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

// ══════════════════════════════════════════════════════════════════
//  InPractice — MemberSolution Model
//  Table: case_member_solutions
//
//  One solution per member per case.
//  avg_rating and ratings_count are cached columns —
//  never computed with aggregates on page load.
// ══════════════════════════════════════════════════════════════════

class MemberSolution extends Model
{
    protected $table = 'case_member_solutions';

    protected $fillable = [
        'case_id',
        'user_id',
        'content',
        'avg_rating',
        'ratings_count',
    ];

    protected $casts = [
        'avg_rating'     => 'float',
        'ratings_count'  => 'integer',
    ];

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

    public function case(): BelongsTo
    {
        return $this->belongsTo(Cases::class, 'case_id');
    }

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

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

    // ── Achievement badge ──────────────────────────────────────
    // Computed from user's highly_rated_solutions_count (cached column)
    // Thresholds: 3 = Rising Voice, 10 = Sharp Mind, 25 = Top Contributor

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

    public static function resolveBadge(int $count): ?array
    {
        if ($count >= 25) {
            return ['key' => 'top_contributor',  'icon' => '🥇', 'min' => 25];
        }
        if ($count >= 10) {
            return ['key' => 'sharp_mind',       'icon' => '🥈', 'min' => 10];
        }
        if ($count >= 3) {
            return ['key' => 'rising_voice',     'icon' => '🥉', 'min' => 3];
        }
        return null;
    }

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

    public function scopeForCase($query, int $caseId)
    {
        return $query->where('case_id', $caseId);
    }

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