<?php

namespace App\Models;

use Database\Factories\PerformanceCardResultFactory;
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\Support\Facades\Auth;

class PerformanceCardResult extends Model
{
    /** @use HasFactory<PerformanceCardResultFactory> */
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'performance_card_id',
        'name',
        'created_by',
    ];

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

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

    /**
     * Get the initiative results that are related to this performance card result.
     */
    public function initiativeResults(): BelongsToMany
    {
        return $this->belongsToMany(InitiativeResult::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();
            }
        });
    }
}
