<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class SaveWorkflowGraphRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user('admin')?->can('manage workflows') ?? false;
    }

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:200'],
            'description' => ['nullable', 'string', 'max:2000'],
            'trigger_event' => ['required', 'string', 'max:100'],
            'is_active' => ['nullable', 'boolean'],
            'priority' => ['nullable', 'integer', 'min:0', 'max:1000'],
            'nodes' => ['required', 'array', 'min:1'],
            'nodes.*.client_id' => ['required', 'string'],
            'nodes.*.type' => ['required', 'in:trigger,condition,action,chain'],
            'nodes.*.config' => ['nullable', 'array'],
            'nodes.*.position_x' => ['required', 'integer'],
            'nodes.*.position_y' => ['required', 'integer'],
            'edges' => ['nullable', 'array'],
            'edges.*.from_client_id' => ['required', 'string'],
            'edges.*.to_client_id' => ['required', 'string'],
            'edges.*.source_port' => ['required', 'in:default,true,false'],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            $nodes = $this->input('nodes', []);
            $hasTrigger = collect($nodes)->contains(fn ($n) => ($n['type'] ?? null) === 'trigger');
            if (! $hasTrigger) {
                $validator->errors()->add('nodes', __('admin/workflows.validation_no_trigger'));
            }
        });
    }
}
