<?php

namespace App\Http\Requests\Tenant;

use App\Support\TenantAuth;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;

class ProfileUpdateRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        $userId = null;

        try {
            $userId = TenantAuth::resolveAdminUser($this)->getKey();
        } catch (\Throwable $e) {
            $userId = null;
        }

        $supportedLocales = config('app.supported_locales');
        if (! is_array($supportedLocales) || empty($supportedLocales)) {
            $supportedLocales = array_filter([
                config('app.locale', 'de'),
                config('app.fallback_locale', 'en'),
            ]);
        }

        return [
            'name' => ['required', 'string', 'max:120'],
            'email' => [
                'required',
                'string',
                'email',
                'max:255',
                Rule::unique('users', 'email')->ignore($userId),
            ],
            'preferred_locale' => [
                'nullable',
                'string',
                Rule::in($supportedLocales),
            ],
            'current_password' => ['required_with:password', 'string'],
            'password' => ['nullable', Password::defaults(), 'confirmed'],
        ];
    }
}
