<?php

namespace App\Models;

use App\Enums\ProjectManner;
use App\Traits\BelongsToOrg;
use Database\Factories\PerformanceCardFactory;
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\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\Auth;

class PerformanceCard extends Model
{
    /** @use HasFactory<PerformanceCardFactory> */
    use BelongsToOrg, HasFactory;

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

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

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

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

    /**
     * Get the grant areas associated with this performance card.
     */
    public function grantAreas(): BelongsToMany
    {
        return $this->belongsToMany(GrantArea::class, 'performance_card_grant_area');
    }

    /**
     * Get the users assigned to this performance card.
     */
    public function assignees(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'performance_card_user', 'performance_card_id', 'user_id');
    }

    /**
     * Get the results for this performance card.
     */
    public function results(): HasMany
    {
        return $this->hasMany(PerformanceCardResult::class);
    }

    /**
     * Get the performance wallet for this performance card.
     */
    public function wallet(): HasOne
    {
        return $this->hasOne(PerformanceWallet::class);
    }

    /**
     * Get the initiatives for this performance card.
     */
    public function initiatives(): HasMany
    {
        return $this->hasMany(Initiative::class);
    }

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

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