<?php

namespace App\Models;

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

class PerformanceWallet extends Model
{
    /** @use HasFactory<PerformanceWalletFactory> */
    use HasFactory, SoftDeletes;

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

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'start_date' => 'date',
            'expected_end_date' => 'date',
        ];
    }

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

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

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

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