<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class AddressRequest extends FormRequest
{
    public function rules(): array
    {
        $rules = [
            'source'    => 'sometimes|string|in:provider,client',
            'source_id' => 'sometimes|integer|min:1',

            'zip_code' => [
                'sometimes',
                'string',
                'regex:/^[0-9]{8}$/',
            ],

            'address'        => 'sometimes|string',
            'number'         => 'nullable|string|max:20',
            'district'       => 'nullable|string|max:255',
            'has_complement' => 'sometimes|boolean',
            'complement'     => 'nullable|string|max:255',
            'nickname'       => 'nullable|string|max:255',
            'instructions'   => 'nullable|string',
            'city_id'        => 'nullable|integer|exists:cities,id',
            'state_id'       => 'nullable|integer|exists:states,id',
            'address_type'   => 'sometimes|in:home,commercial,other',
            'is_primary'     => 'sometimes|boolean',
            'latitude'       => 'nullable|numeric|between:-90,90',
            'longitude'      => 'nullable|numeric|between:-180,180',
        ];

        if ($this->isMethod('post')) {
            $rules['source'] = 'required|string|in:provider,client';

            $rules['source_id'] = [
                'required',
                'integer',
                'min:1',
            ];

            $rules['zip_code'] = [
                'required',
                'string',
                'regex:/^[0-9]{8}$/',
            ];

            $rules['address']      = 'required|string';
            $rules['address_type'] = 'required|in:home,commercial,other';
        }

        return $rules;
    }

    public function messages(): array
    {
        return [
            'zip_code.regex'  => __('validation.custom.zip_code.invalid'),
            'source.in'       => __('validation.custom.source.invalid'),
            'address_type.in' => __('validation.custom.address_type.invalid'),
        ];
    }
}
