<?php

namespace App\Http\Requests\Admin\Hr;

use App\Enums\EmploymentStatus;
use App\Enums\Gender;
use App\Enums\Permission;
use App\Enums\Role;
use App\Rules\PhoneNumber;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class EmployeeRequest extends FormRequest
{
    public function authorize(): bool
    {
        $permission = $this->isMethod('POST')
            ? Permission::EMPLOYEES_CREATE
            : Permission::EMPLOYEES_UPDATE;

        return $this->user()?->can($permission->value) ?? false;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $isOwner = $this->role === Role::OWNER->value;

        $rules = [
            'email' => ['required', 'email', 'max:100', Rule::unique('users', 'email')->ignore($this->route('user')?->id)],
            'username' => ['required', 'string', 'max:20', 'alpha_dash', Rule::unique('users', 'username')->ignore($this->route('user')?->id)],
            'full_name' => ['required', 'string', 'max:200'],
            'phone_number' => ['nullable', 'string', 'max:20', new PhoneNumber],
            'gender' => ['nullable', Rule::enum(Gender::class)],
            'birth_date' => ['nullable', 'date', 'before:today'],
            'address' => ['nullable', 'string'],
            'role' => ['required', Rule::in(Role::assignableValues())],
            'profile_photo' => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
            'remove_profile_photo_ids' => ['nullable', 'array'],
            'remove_profile_photo_ids.*' => ['integer'],
        ];

        if (! $isOwner) {
            $rules['join_date'] = ['required', 'date'];
            $rules['employment_status'] = ['required', Rule::enum(EmploymentStatus::class)];
            $rules['base_salary'] = ['required', 'integer', 'min:0'];
        }

        return $rules;
    }

    /**
     * @return array<string, string>
     */
    public function attributes(): array
    {
        return [
            'email' => 'Email',
            'username' => 'Username',
            'full_name' => 'Nama Lengkap',
            'phone_number' => 'Nomor Telepon',
            'gender' => 'Jenis Kelamin',
            'birth_date' => 'Tanggal Lahir',
            'address' => 'Alamat',
            'profile_photo' => 'Foto Profil',
            'role' => 'Role',
            'join_date' => 'Tanggal Bergabung',
            'employment_status' => 'Status Kepegawaian',
            'base_salary' => 'Gaji Pokok',
        ];
    }
}
