<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

class StoreOfferFinanceFieldConfigRequest extends FormRequest
{
    public function authorize(): bool
    {
        return Auth::check();
    }

    protected function prepareForValidation(): void
    {
        if (!$this->filled('key') && $this->filled('label')) {
            $this->merge([
                'key' => Str::slug((string) $this->input('label'), '_'),
            ]);
        }
    }

    public function rules(): array
    {
        return [
            'key' => [
                'required',
                'string',
                'max:64',
                'regex:/^[a-z][a-z0-9_]*$/',
                Rule::unique('offer_finance_field_configs', 'key'),
            ],
            'label' => ['required', 'string', 'max:255'],
            'type' => ['required', Rule::in(['text', 'number', 'currency'])],
            'suffix' => ['nullable', 'string', 'max:32'],
            'position' => ['nullable', 'integer', 'min:0'],
        ];
    }
}
