<?php

namespace Modules\Approval\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Modules\Approval\Enums\ApprovalStepStatusEnum;
use Modules\Approval\Models\Traits\HasActor;
use Modules\Approval\Models\Traits\HasApprovalRequest;

class ApprovalRequestStep extends Model
{
    use HasApprovalRequest,
        HasActor;

    protected $fillable = [
        'approval_request_id',
        'approval_workflow_step_id',
        'level',
        'permission_name',
        'status',
        'action_by',
        'action_at',
        'remarks',
    ];

    protected $casts = [
        'action_at' => 'datetime',
    ];

    public function workflowStep(): BelongsTo
    {
        return $this->belongsTo(ApprovalWorkflowStep::class, 'approval_workflow_step_id');
    }

    public function isCurrent(): bool
    {
        if (!$this->relationLoaded('approvalRequest')) {
            $this->loadMissing('approvalRequest:id,current_level');
        }

        return $this->level === $this->approvalRequest->current_level;
    }

    public function state(): string
    {
        if ($this->status === ApprovalStepStatusEnum::APPROVED->value) {
            return 'completed';
        }

        if ($this->status === ApprovalStepStatusEnum::REJECTED->value) {
            return 'rejected';
        }

        if ($this->isCurrent()) {
            return 'current';
        }

        return 'waiting';
    }
}
