<?php

namespace App\Http\Requests\Staff;

use App\Enums\UserStatus;
use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
use Illuminate\Validation\Validator;

class UpdateStaffRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('STAFF_UPDATE') ?? false;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $userId = $this->route('staff')?->id ?? $this->route('staff');

        return [
            'name' => ['sometimes', 'required', 'string', 'max:255'],
            'email' => ['sometimes', 'required', 'email', 'max:255', Rule::unique('users', 'email')->ignore($userId)],
            'phone' => ['nullable', 'string', 'max:50'],
            'password' => ['nullable', Password::defaults()],
            'status' => ['nullable', Rule::enum(UserStatus::class)],
            'department_id' => ['nullable', 'exists:departments,id'],
            'designation_id' => ['nullable', 'exists:designations,id'],
            'role' => ['nullable', 'exists:roles,id'],
            'roles' => ['nullable', 'array'],
            'roles.*' => ['string', 'exists:roles,name'],
        ];
    }

    protected function prepareForValidation(): void
    {
        if ($this->has('role')) {
            if ($this->filled('role')) {
                $roleName = Role::query()->whereKey($this->input('role'))->value('name');

                if ($roleName) {
                    $this->merge(['roles' => [$roleName]]);
                }
            } else {
                $this->merge(['roles' => []]);
            }
        }
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            /** @var User|null $staff */
            $staff = $this->route('staff');

            if (! $staff?->isPrimaryAdmin()) {
                return;
            }

            if ($this->input('status') === UserStatus::Suspended->value) {
                $validator->errors()->add('status', 'The primary administrator cannot be suspended.');
            }

            if ($this->filled('role')) {
                $roleName = Role::query()->whereKey($this->input('role'))->value('name');

                if ($roleName !== config('permissions.super_admin_role', 'Super Admin')) {
                    $validator->errors()->add('role', 'The primary administrator must remain a Super Admin.');
                }
            }
        });
    }
}
