<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Score extends Model
{
    use HasFactory;

    protected $fillable = ['competition_id', 'athlete_id', 'apparatus_id', 'round_number', 'group_id', 'd_score', 'e1_score', 'e2_score', 'e3_score', 'e4_score', 'bonus', 'cr_score', 'nd_score', 'final_score', 'created_by_user_id'];

    public function competition()
    {
        return $this->belongsTo(Competition::class);
    }
    public function athlete()
    {
        return $this->belongsTo(Athlete::class);
    }
    public function apparatus()
    {
        return $this->belongsTo(Apparatus::class);
    }
    public function group()
    {
        return $this->belongsTo(Group::class);
    }
    public function judge()
    {
        return $this->belongsTo(User::class, 'created_by_user_id');
    }
    public function getFinalTotalAttribute(): float
    {
        // Prefer the stored final_score if present
        if (!is_null($this->final_score)) {
            return (float) $this->final_score;
        }
        return (float) $this->calculateFinalScore();
    }

    public function getAverageEScore()
    {
        return collect([$this->e1_score, $this->e2_score, $this->e3_score, $this->e4_score])
            ->filter(fn($v) => $v !== null)
            ->average() ?? 0;
    }

    public function calculateFinalScore()
    {
        $avgE = $this->getAverageEScore();
        if (($this->competition && $this->competition->scoring_type === 'American') || $this->apparatus_id == 3) {
            return round($this->d_score + $avgE, 2);
        }
        return round($this->d_score + (10 - $avgE) + $this->bonus + $this->cr_score - $this->nd_score, 2);
    }

    protected static function booted()
    {
        static::saving(function ($s) {
            if ($s->final_score === null) {
                $s->final_score = $s->calculateFinalScore();
            }
        });
    }
}
