<?php

namespace App\Domain\Workflow\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PipelineTransition extends Model
{
    protected $guarded = ['id'];

    protected function casts(): array
    {
        return [
            'allowed_roles' => 'array',
            'requires_reason' => 'boolean',
            'is_active' => 'boolean',
        ];
    }

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

    public function fromStage(): BelongsTo
    {
        return $this->belongsTo(PipelineStage::class, 'from_stage_id');
    }

    public function toStage(): BelongsTo
    {
        return $this->belongsTo(PipelineStage::class, 'to_stage_id');
    }

    /** @param array<int, string> $roles */
    public function allowsRoles(array $roles): bool
    {
        // No restriction configured means the change_stage permission is enough.
        if (blank($this->allowed_roles)) {
            return true;
        }

        return array_intersect($this->allowed_roles, $roles) !== [];
    }
}
