<?php

namespace App\Models;

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

class Initiative extends Model
{
    /** @use HasFactory<InitiativeFactory> */
    use HasFactory, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'performance_card_id',
        'name',
        'description',
        'start_date',
        'expected_end_date',
        '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 initiative belongs to.
     */
    public function performanceCard(): BelongsTo
    {
        return $this->belongsTo(PerformanceCard::class);
    }

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

    /**
     * Get the grant areas that this initiative is responsible for.
     */
    public function grantAreas(): BelongsToMany
    {
        return $this->belongsToMany(GrantArea::class, 'initiative_grant_area');
    }

    /**
     * Get the operation goals for this initiative.
     */
    public function operationGoals(): HasMany
    {
        return $this->hasMany(InitiativeOperationGoal::class);
    }

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

    /**
     * Get the projects for this initiative.
     */
    public function projects(): HasMany
    {
        return $this->hasMany(InitiativeProject::class);
    }

    /**
     * Get the project charters for this initiative.
     */
    public function charters(): HasMany
    {
        return $this->hasMany(ProjectCharter::class);
    }

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

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