<?php

namespace App\Models;

use App\Enums\RiskLevel;
use App\Traits\BelongsToOrg;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Auth;

class ProjectCharterRisk extends Model
{
    use BelongsToOrg, HasFactory;

    protected $fillable = [
        'org_id',
        'project_charter_id',
        'name',
        'description',
        'incident_likelihood',
        'impact_level',
        'impact_on_cost',
        'impact_on_time',
        'mitigation_plan',
        'contingency_plan',
        'financial_contingency',
        'technical_contingency',
        'created_by',
    ];

    protected $casts = [
        'incident_likelihood' => RiskLevel::class,
        'impact_level' => RiskLevel::class,
        'impact_on_cost' => 'decimal:2',
        'impact_on_time' => 'integer', // in days
        'financial_contingency' => 'decimal:2',
        'technical_contingency' => 'decimal:2',
    ];

    public function projectCharter(): BelongsTo
    {
        return $this->belongsTo(ProjectCharter::class);
    }

    public function createdBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function getRiskScoreAttribute(): float
    {
        $likelihoodScore = match ($this->incident_likelihood) {
            RiskLevel::LOW => 1,
            RiskLevel::MEDIUM => 2,
            RiskLevel::HIGH => 3,
            default => 0,
        };

        $impactScore = match ($this->impact_level) {
            RiskLevel::LOW => 1,
            RiskLevel::MEDIUM => 2,
            RiskLevel::HIGH => 3,
            default => 0,
        };

        return $likelihoodScore * $impactScore;
    }

    public function getRiskCategoryAttribute(): string
    {
        $score = $this->risk_score;

        return match (true) {
            $score <= 2 => 'low',
            $score <= 6 => 'medium',
            default => 'high',
        };
    }

    public function getTotalFinancialImpactAttribute(): float
    {
        return ($this->impact_on_cost ?? 0) + ($this->financial_contingency ?? 0);
    }

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

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