<?php

namespace App\Models;

use App\Enums\PredictionSource;
use App\Enums\TrendDirection;
use Database\Factories\PricePredictionFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

#[Fillable(['predicted_for', 'source', 'direction', 'confidence', 'reasoning', 'generated_at'])]
class PricePrediction extends Model
{
    /** @use HasFactory<PricePredictionFactory> */
    use HasFactory;

    public $timestamps = false;

    protected function casts(): array
    {
        return [
            'predicted_for' => 'date',
            'source' => PredictionSource::class,
            'direction' => TrendDirection::class,
            'confidence' => 'integer',
            'generated_at' => 'datetime',
        ];
    }

    /**
     * Order by source quality: llm_with_context → llm → ewma.
     * Use this whenever reading the "best" prediction for a given date.
     *
     * @param  Builder<PricePrediction>  $query
     * @return Builder<PricePrediction>
     */
    public function scopeBestFirst(Builder $query): Builder
    {
        $priority = [
            PredictionSource::LlmWithContext->value,
            PredictionSource::Llm->value,
            PredictionSource::Ewma->value,
        ];

        $cases = '';
        foreach ($priority as $rank => $source) {
            $cases .= " WHEN '$source' THEN $rank";
        }

        return $query->orderByRaw("CASE source$cases ELSE ".count($priority).' END');
    }
}
