<?php

namespace App\Http\Requests;

use App\Enums\ClientStatus;
use App\Enums\LegalForm;
use BenSampo\Enum\Rules\EnumValue;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

class StoreClientRequest extends FormRequest
{
    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        if ($this->has('internal_responsible_id') && $this->internal_responsible_id === '') {
            $this->merge(['internal_responsible_id' => null]);
        }
    }

    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return $this->user() !== null;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'company_name' => ['required', 'string', 'max:255'],
            'legal_form' => ['required', new EnumValue(LegalForm::class)],
            'ice' => ['nullable', 'string', 'max:50'],
            'fiscal_id' => ['nullable', 'string', 'max:50'],
            'rc' => ['nullable', 'string', 'max:50'],
            'cnss' => ['nullable', 'string', 'max:50'],
            'patente' => ['nullable', 'string', 'max:50'],
            'contacts' => ['required', 'array', 'min:1', 'max:20'],
            'contacts.*.full_name' => ['required', 'string', 'max:255'],
            'contacts.*.job_title' => ['nullable', 'string', 'max:255'],
            'contacts.*.email' => ['nullable', 'string', 'email', 'max:255'],
            'contacts.*.phone' => ['nullable', 'string', 'max:50'],
            'contacts.*.is_principal' => ['required', 'boolean'],
            'internal_responsible_id' => ['nullable', 'integer', 'exists:users,id'],
            'status' => ['nullable', Rule::in(ClientStatus::getValues())],
            'internal_notes' => ['nullable', 'string', 'max:65535'],
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            $contacts = $this->input('contacts', []);
            $principalCount = collect($contacts)->where('is_principal', true)->count();
            if ($principalCount !== 1) {
                $validator->errors()->add('contacts', 'Exactement un responsable doit être marqué comme principal.');
            }
        });
    }
}
