<?php

declare(strict_types=1);

namespace App\Http\Requests\Masters;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

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

    /**
     * @return array<string, array<int, mixed>>
     */
    public function rules(): array
    {
        return [
            'name' => [
                'required',
                'string',
                'max:100',
                /*
                 | Deliberately NOT withoutTrashed(): `name` is unique across
                 | every row, soft-deleted included. Validating only live rows
                 | would let this pass and then hit a duplicate-key error at
                 | insert. The message below points at the deleted list instead.
                 */
                Rule::unique('teams', 'name'),
            ],
            'code' => [
                'nullable',
                'string',
                'max:20',
                'regex:/^[A-Z0-9][A-Z0-9\-]*$/',
                Rule::unique('teams', 'code'),
            ],
            'head_employee_id' => [
                'nullable',
                'integer',
                Rule::exists('employees', 'id')->whereNull('deleted_at'),
            ],
            'is_active' => ['required', 'boolean'],
        ];
    }

    /**
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'name.unique' => __('A team with this name already exists. It may be in the deleted list — restore it instead of creating a duplicate.'),
            'code.unique' => __('A team with this code already exists. It may be in the deleted list.'),
            'code.regex' => __('The code may contain only letters, numbers and hyphens.'),
            'head_employee_id.exists' => __('The selected employee no longer exists.'),
        ];
    }

    protected function prepareForValidation(): void
    {
        $code = trim((string) $this->input('code'));
        $headEmployeeId = $this->input('head_employee_id');

        $this->merge([
            'name' => trim((string) $this->input('name')),
            'code' => $code === '' ? null : mb_strtoupper($code),
            'head_employee_id' => ($headEmployeeId === null || $headEmployeeId === '') ? null : (int) $headEmployeeId,
            'is_active' => $this->boolean('is_active'),
        ]);
    }
}
