<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class EscalationPolicy extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'description', 'enabled', 'created_by'];
    protected $casts = ['enabled' => 'boolean'];

    public function steps(): HasMany
    {
        return $this->hasMany(EscalationStep::class, 'policy_id')->orderBy('step_number');
    }

    /**
     * Resolves the targets of every step into a flat list of {user_id, channel}
     * pairs the dispatcher can act on. Roles are expanded to user IDs at lookup
     * time so role membership changes take effect immediately.
     */
    public function resolvedSteps(): array
    {
        return $this->steps->map(function (EscalationStep $step) {
            $targets = $step->targets ?? [];
            $userIds = collect($targets['users'] ?? []);

            // Expand role-based targets.
            if (!empty($targets['roles'])) {
                $userIds = $userIds->merge(
                    User::whereIn('role', $targets['roles'])->where('status', 'active')->pluck('id')
                );
            }

            return [
                'step_number' => $step->step_number,
                'delay_seconds' => $step->delay_seconds,
                'channels' => $step->channels ?? [],
                'user_ids' => $userIds->unique()->values()->all(),
                'external' => $targets['external'] ?? [],
                'only_if_unacknowledged' => (bool) $step->only_if_unacknowledged,
            ];
        })->all();
    }
}
