<?php

declare(strict_types=1);

namespace ImovelZapAi\Organizations\Application\Actions;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

final class UpdateUserProfileAction
{
    /**
     * @param  array{
     *     name: string,
     *     email: string,
     *     phone?: string|null,
     *     creci?: string|null,
     *     password?: string|null,
     *     current_password?: string|null,
     * }  $data
     */
    public function execute(User $user, array $data): User
    {
        if (! empty($data['password'])) {
            if (empty($data['current_password']) || ! Hash::check((string) $data['current_password'], (string) $user->password)) {
                throw ValidationException::withMessages([
                    'current_password' => ['Senha atual incorreta.'],
                ]);
            }
        }

        $emailTaken = User::query()
            ->where('email', $data['email'])
            ->whereKeyNot($user->id)
            ->exists();

        if ($emailTaken) {
            throw ValidationException::withMessages([
                'email' => ['Este e-mail já está em uso.'],
            ]);
        }

        $payload = [
            'name' => trim($data['name']),
            'email' => strtolower(trim($data['email'])),
            'phone' => $data['phone'] ?? null,
            'creci' => $data['creci'] ?? null,
        ];

        if (! empty($data['password'])) {
            $payload['password'] = $data['password'];
        }

        $user->forceFill($payload)->save();

        return $user->fresh() ?? $user;
    }
}
