<?php

namespace App\Models;

use Database\Factories\InitiativeResultFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;

class InitiativeResult extends Model
{
    /** @use HasFactory<InitiativeResultFactory> */
    use HasFactory, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'initiative_id',
        'expected_q1',
        'actual_q1',
        'expected_q2',
        'actual_q2',
        'expected_q3',
        'actual_q3',
        'expected_q4',
        'actual_q4',
        'created_by',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'expected_q1' => 'decimal:2',
            'actual_q1' => 'decimal:2',
            'expected_q2' => 'decimal:2',
            'actual_q2' => 'decimal:2',
            'expected_q3' => 'decimal:2',
            'actual_q3' => 'decimal:2',
            'expected_q4' => 'decimal:2',
            'actual_q4' => 'decimal:2',
        ];
    }

    /**
     * Get the initiative that this result belongs to.
     */
    public function initiative(): BelongsTo
    {
        return $this->belongsTo(Initiative::class);
    }

    /**
     * Get the user who created this result.
     */
    public function createdBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get the performance card results that this initiative result is related to.
     */
    public function performanceCardResults(): BelongsToMany
    {
        return $this->belongsToMany(PerformanceCardResult::class, 'initiative_result_performance_card_result');
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (Auth::check() && ! $model->created_by) {
                $model->created_by = Auth::id();
            }
        });
    }
}
