<?php

namespace App\Http\Requests\MenuGroup;

use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;

class SyncUserMenuGroupsRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    /**
     * @return array<string, ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'assignments' => [
                'required',
                'array',
                'min:1',
            ],
            'assignments.*.menu_group_id' => [
                'required',
                'integer',
                'exists:menu_groups,id',
            ],
            'assignments.*.tenant_id' => [
                'nullable',
                'integer',
                'exists:tenants,id',
            ],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            $assignments = $this->input('assignments', []);
            $seen = [];

            foreach ($assignments as $index => $assignment) {
                $menuGroupId = $assignment['menu_group_id'] ?? null;
                $tenantId = $assignment['tenant_id'] ?? null;
                $key = $menuGroupId.'|'.($tenantId ?? 'null');

                if (isset($seen[$key])) {
                    $validator->errors()->add(
                        "assignments.$index",
                        'Kombinasi menu_group_id dan tenant_id harus unik.'
                    );
                }

                $seen[$key] = true;
            }
        });
    }
}
