<?php

namespace App\Http\Requests;

use App\Services\DealershipBulkUpdateService;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class DealershipBulkUpdateRequest extends FormRequest
{
    private ?array $allowedFields = null;

    public function authorize(): bool
    {
        return Auth::check();
    }

    public function rules(): array
    {
        $allowedFields = $this->getAllowedFields();

        return [
            'mode' => ['required', 'string', Rule::in(['same', 'different'])],
            'dealership_ids' => ['required', 'array', 'max:100'],
            'dealership_ids.*' => ['required', 'integer', 'exists:dealerships,id'],

            // Same mode validation
            'field' => [
                'required_if:mode,same',
                'nullable',
                'string',
                Rule::in($allowedFields),
            ],
            'value' => ['required_if:mode,same', 'nullable'],

            // Different mode validation
            'updates' => ['required_if:mode,different', 'nullable', 'array'],
            'updates.*' => ['array'],
            'updates.*.*' => ['nullable'],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            if ($this->input('mode') === 'different') {
                $this->validateDifferentModeUpdates($validator);
            }
        });
    }

    private function validateDifferentModeUpdates($validator): void
    {
        $updates = $this->input('updates', []);
        $dealershipIds = $this->input('dealership_ids', []);
        $allowedFields = $this->getAllowedFields();

        foreach ($updates as $dealershipId => $fields) {
            if (!in_array((int) $dealershipId, array_map('intval', $dealershipIds))) {
                $validator->errors()->add(
                    "updates.{$dealershipId}",
                    "Dealership ID {$dealershipId} is not in the selected dealerships list."
                );
                continue;
            }

            if (!is_array($fields)) {
                continue;
            }

            foreach (array_keys($fields) as $field) {
                if (!in_array($field, $allowedFields)) {
                    $validator->errors()->add(
                        "updates.{$dealershipId}.{$field}",
                        "Field '{$field}' is not allowed for bulk update."
                    );
                }
            }
        }
    }

    private function getAllowedFields(): array
    {
        if ($this->allowedFields === null) {
            $service = app(DealershipBulkUpdateService::class);
            $this->allowedFields = $service->getAllowedFields();
        }

        return $this->allowedFields;
    }

    public function messages(): array
    {
        return [
            'mode.required' => 'Please select an update mode.',
            'mode.in' => 'Invalid update mode. Must be "same" or "different".',
            'dealership_ids.required' => 'Please select at least one dealership.',
            'dealership_ids.max' => 'You can only update up to 100 dealerships at a time.',
            'dealership_ids.*.exists' => 'One or more selected dealerships do not exist.',
            'field.required_if' => 'Please select a field to update.',
            'field.in' => 'The selected field is not allowed for bulk update.',
            'value.required_if' => 'Please provide a value for the selected field.',
            'updates.required_if' => 'Please provide updates for the selected dealerships.',
        ];
    }
}
