<?php

namespace Daylight\Core\Http\Requests\Settings\ShippingZones;

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

class StoreShippingZoneRequest extends FormRequest
{
    public function authorize(): bool
    {
        return auth()->check() && auth()->user()->can('update:settings');
    }

    public function rules(): array
    {
        return [
            'name' => ['required', 'string'],
            'countries' => ['required', 'array'],
            'countries.*' => ['required', 'string', 'exists:countries,id'],
            'rules' => ['required', 'array'],
            'rules.*.*.price' => ['required', 'numeric'],
            'max_amount' => ['nullable', 'numeric'],
            'free_shipping_above' => ['nullable', 'numeric'],
            'free_shipping_postal_prefix_list' => ['nullable', 'string', 'max:500'],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            $value = $this->input('free_shipping_postal_prefix_list');

            if (! is_string($value) || trim($value) === '') {
                return;
            }

            foreach (explode(',', $value) as $part) {
                $p = trim($part);

                if ($p === '') {
                    continue;
                }

                if (! preg_match('/^\d+$/', $p)) {
                    $validator->errors()->add(
                        'free_shipping_postal_prefix_list',
                        __('daylight::settings.free_shipping_postal_prefixes_invalid_digit')
                    );

                    break;
                }
            }
        });
    }
}
