<?php

namespace App\Http\Requests;

use App\Enums\GenderEnum;
use App\Enums\LanguageEnum;
use App\Enums\UserTypeEnum;
use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UserRequest extends FormRequest
{
    public function rules(): array
    {
        $rules = [
            'avatar' => 'sometimes|string|nullable',
            'name'   => 'sometimes|string|nullable',

            'email' => [
                'sometimes',
                'email',
                Rule::unique('users', 'email')
                    ->where('type', $this->emailUniqueType())
                    ->ignore($this->route('id')),
            ],

            'password' => 'sometimes|string|nullable',
            'type'     => ['sometimes', Rule::enum(UserTypeEnum::class)],
            'language' => ['sometimes', Rule::enum(LanguageEnum::class)],
            'phone'    => 'sometimes|string|nullable',
            'gender'   => 'sometimes|string|in:'.implode(',', GenderEnum::toArray()),
            'push_notifications_enabled' => 'sometimes|boolean',
        ];

        if ($this->isMethod('post')) {
            $rules['name']  = 'required|string|max:255';
            $rules['email'] = [
                'required',
                'email',
                Rule::unique('users', 'email')->where('type', $this->emailUniqueType()),
            ];
            $rules['password'] = 'required|string|min:6';

            if (! $this->has('language')) {
                $this->merge(['language' => LanguageEnum::PORTUGUESE->value]);
            }
        }

        return $rules;
    }

    private function emailUniqueType(): string
    {
        if ($this->filled('type')) {
            return $this->input('type');
        }

        $id   = $this->route('id');
        $type = $id ? User::query()->whereKey($id)->value('type') : null;

        if ($type instanceof UserTypeEnum) {
            $type = $type->value;
        }

        return $type ?? UserTypeEnum::USER->value;
    }
}
