<?php

declare(strict_types=1);

namespace App\Models;

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

class ReportItem extends Model
{
    protected $guarded = ['id', 'created_at', 'updated_at'];

    protected $casts = [
        'min_value' => 'decimal:3',
        'max_value' => 'decimal:3',
        'value' => 'decimal:3',
        'avg_value' => 'decimal:3',
    ];

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

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

    public function resolveAverage(): ?float
    {
        if ($this->avg_value !== null) {
            return (float) $this->avg_value;
        }

        if ($this->min_value !== null && $this->max_value !== null) {
            return ((float) $this->min_value + (float) $this->max_value) / 2;
        }

        return $this->value !== null ? (float) $this->value : null;
    }
}
