<?php

declare(strict_types=1);

namespace App\Http\Requests\Employee;

use App\Enums\EmployeeStatus;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

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

    /**
     * @return array<string, array<int, mixed>>
     */
    public function rules(): array
    {
        return [
            'employee_code' => [
                'required',
                'string',
                'max:30',
                // Unique across all rows, soft-deleted included: reusing a
                // former employee's code means restoring them, not creating a
                // duplicate that would collide on restore.
                Rule::unique('employees', 'employee_code'),
            ],
            'first_name' => ['required', 'string', 'max:80'],
            'last_name' => ['nullable', 'string', 'max:80'],
            'email' => [
                'nullable',
                'string',
                'email',
                'max:160',
                Rule::unique('employees', 'email'),
            ],
            'personal_email' => ['nullable', 'string', 'email', 'max:160'],
            'phone' => ['nullable', 'string', 'max:20'],
            'team_id' => [
                'nullable',
                'integer',
                Rule::exists('teams', 'id')->whereNull('deleted_at'),
            ],
            'designation' => ['nullable', 'string', 'max:120'],
            'squad' => ['nullable', 'string', 'max:100'],
            'location_id' => [
                'nullable',
                'integer',
                Rule::exists('locations', 'id')->whereNull('deleted_at'),
            ],
            'status' => ['required', Rule::enum(EmployeeStatus::class)],
            'date_of_joining' => ['nullable', 'date'],
            'date_of_exit' => ['nullable', 'date', 'after_or_equal:date_of_joining'],
            'notes' => ['nullable', 'string', 'max:2000'],
        ];
    }

    /**
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'employee_code.unique' => __('An employee with this code already exists. They may be in the deleted list — restore them instead of creating a duplicate.'),
            'email.unique' => __('An employee with this email address already exists. They may be in the deleted list.'),
            'team_id.exists' => __('The selected team no longer exists.'),
            'location_id.exists' => __('The selected location no longer exists.'),
            'date_of_exit.after_or_equal' => __('The exit date cannot be before the date of joining.'),
        ];
    }

    protected function prepareForValidation(): void
    {
        $this->merge(EmployeeRules::normalise($this));
    }
}
