<?php

namespace App\Domain\Workflow\Models;

use App\Domain\Organization\Models\Company;
use App\Support\Concerns\HasUuid;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Pipeline extends Model
{
    use HasFactory, HasUuid, SoftDeletes;

    protected $guarded = ['id', 'uuid'];

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

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

    public function stages(): HasMany
    {
        return $this->hasMany(PipelineStage::class)->orderBy('sequence');
    }

    public function transitions(): HasMany
    {
        return $this->hasMany(PipelineTransition::class);
    }

    public function initialStage(): ?PipelineStage
    {
        return $this->stages()->where('is_initial', true)->where('is_active', true)->first();
    }
}
