<?php

namespace App\Http\Requests\Admin;

use App\Models\Setting;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;

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

    public function rules(): array
    {
        return [
            'settings' => ['required', 'array'],
            'settings.token_scope' => ['sometimes', 'in:doctor_location,location'],
            'settings.token_start' => ['sometimes', 'integer', 'min:1', 'max:9999'],
            'settings.token_min' => ['sometimes', 'integer', 'min:1', 'max:9999'],
            'settings.token_max' => ['sometimes', 'integer', 'min:1', 'max:9999'],
            'settings.reminder_offsets_minutes' => ['sometimes', 'array', 'min:1', 'max:10'],
            'settings.reminder_offsets_minutes.*' => ['integer', 'min:1', 'max:10080', 'distinct'],
            'settings.patient_self_booking_enabled' => ['sometimes', 'boolean'],
            'settings.appointment_types' => ['sometimes', 'array', 'min:1', 'max:30'],
            'settings.appointment_types.*' => ['required', 'string', 'max:80', 'regex:/^[a-z0-9_\-]+$/', 'distinct'],
            'settings.payment_methods' => ['sometimes', 'array', 'min:1', 'max:30'],
            'settings.payment_methods.*' => ['required', 'string', 'max:60', 'regex:/^[a-z0-9_\-]+$/', 'distinct'],
        ];
    }

    public function after(): array
    {
        return [function (Validator $validator) {
            $settings = $this->input('settings', []);
            $current = collect(Setting::query()
                ->where('organization_id', $this->user()->organization_id)
                ->get())
                ->mapWithKeys(fn ($row) => [$row->key => $row->value])
                ->all();

            $min = (int) ($settings['token_min'] ?? $current['token_min'] ?? 1);
            $max = (int) ($settings['token_max'] ?? $current['token_max'] ?? 9999);
            $start = (int) ($settings['token_start'] ?? $current['token_start'] ?? 1);

            if ($min > $max) {
                $validator->errors()->add('settings.token_min', 'Token minimum cannot be greater than token maximum.');
            }
            if ($start < $min || $start > $max) {
                $validator->errors()->add('settings.token_start', 'Token start must be inside the configured token range.');
            }
        }];
    }
}
