<?php

declare(strict_types=1);

namespace App\Http\Requests;

use App\Support\InnValidator;
use App\Support\PhoneNormalizer;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdateRequisitesRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user() !== null;
    }

    /** @return array<string, mixed> */
    public function rules(): array
    {
        $subjectType = (string) $this->input('subject_type');

        return [
            'subject_type' => ['required', Rule::in(['individual', 'sole_proprietor', 'legal_entity'])],
            'contact_name' => ['required', 'string', 'max:255'],
            'contact_phone' => ['required', 'string', function ($attr, $value, $fail) {
                if (PhoneNormalizer::normalize((string) $value) === null) {
                    $fail('Некорректный телефон.');
                }
            }],
            'inn' => [
                Rule::requiredIf(in_array($subjectType, ['legal_entity', 'sole_proprietor'], true)),
                'nullable', 'string',
                function ($attr, $value, $fail) use ($subjectType) {
                    if (in_array($subjectType, ['legal_entity', 'sole_proprietor'], true)
                        && is_string($value) && $value !== ''
                        && ! InnValidator::isValid($value, $subjectType)) {
                        $fail('Некорректный ИНН (контрольная цифра).');
                    }
                },
            ],
            'legal_name' => ['nullable', 'string', 'max:255'],
            'kpp' => ['nullable', 'string', 'regex:/^\d{9}$/'],
            'ogrn' => ['nullable', 'string', 'regex:/^(\d{13}|\d{15})$/'],
            'legal_address' => ['nullable', 'string'],
            'bank_name' => ['nullable', 'string', 'max:255'],
            'bank_bik' => ['nullable', 'string', 'regex:/^\d{9}$/'],
            'bank_account' => ['nullable', 'string', 'regex:/^\d{20}$/'],
            'corr_account' => ['nullable', 'string', 'regex:/^\d{20}$/'],
        ];
    }
}
