<?php

namespace App\Http\Requests\Admin\ProductConfigOptionDependency;

use App\Models\ProductConfigOptionDependency;
use App\Models\ProductConfigOptionGroup;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

/**
 * PRC-686 — Bağımlı configurable option kuralı ekleme doğrulaması.
 *
 * Kaynak ve hedef option AYNI gruba ait olmalı (kural grup kapsamında) ve
 * birbirinden farklı olmalı. equals/not_equals → source_value_id gerekli;
 * in → source_value_ids gerekli; any → değer gerekmez.
 */
class StoreDependencyRequest extends FormRequest
{
    public function authorize(): bool
    {
        $group = $this->route('group');
        if (! $group instanceof ProductConfigOptionGroup) {
            return false;
        }

        return ($this->user('admin') ?? $this->user())?->can('update', $group) ?? false;
    }

    public function rules(): array
    {
        $group = $this->route('group');
        $groupId = $group instanceof ProductConfigOptionGroup ? $group->id : (int) $group;

        return [
            'source_option_id' => [
                'required', 'integer',
                Rule::exists('product_config_options', 'id')->where('group_id', $groupId)->whereNull('archived_at'),
            ],
            'target_option_id' => [
                'required', 'integer', 'different:source_option_id',
                Rule::exists('product_config_options', 'id')->where('group_id', $groupId)->whereNull('archived_at'),
            ],
            'operator' => ['required', Rule::in(ProductConfigOptionDependency::OPERATORS)],
            'action' => ['required', Rule::in(ProductConfigOptionDependency::ACTIONS)],

            // equals / not_equals → tek değer (kaynak option'a ait value id).
            'source_value_id' => [
                'nullable',
                Rule::requiredIf(fn () => in_array($this->input('operator'), ['equals', 'not_equals'], true)),
                'integer',
                Rule::exists('product_config_option_values', 'id')
                    ->where('option_id', (int) $this->input('source_option_id')),
            ],

            // in → değer id listesi.
            'source_value_ids' => [
                'nullable', 'array',
                Rule::requiredIf(fn () => $this->input('operator') === 'in'),
            ],
            'source_value_ids.*' => [
                'integer',
                Rule::exists('product_config_option_values', 'id')
                    ->where('option_id', (int) $this->input('source_option_id')),
            ],
        ];
    }

    protected function prepareForValidation(): void
    {
        // Boş string value'ları null'a indir (form select boş seçim → '').
        if ($this->input('source_value_id') === '') {
            $this->merge(['source_value_id' => null]);
        }
    }
}
