<?php

declare(strict_types=1);

namespace Builder\Core\Http\Controllers\Account;

use Builder\Core\Extensions\Account\AccountProfile;
use Builder\Core\Foundation\Account\AccountDefinition;
use Builder\Core\Foundation\Registry;
use Builder\Core\Http\Requests\Account\UpdateProfileRequest;
use Illuminate\Http\RedirectResponse;

final class UpdateAccountController
{
    public function __construct(private readonly Registry $registry) {}

    public function __invoke(UpdateProfileRequest $request): RedirectResponse
    {
        $user = $request->user();
        assert($user !== null);
        $definition = $this->makeDefinition();

        $data = $request->validated();

        $user->fill(array_filter($data, fn (string $k) => ! in_array($k, ['current_password', 'password', 'password_confirmation'], true), ARRAY_FILTER_USE_KEY));

        foreach ($definition->getHooks() as $hook) {
            if ($hook->getEvent() === 'saving') {
                $hook->execute($user, $data);
            }
        }

        $user->save();

        foreach ($definition->getHooks() as $hook) {
            if ($hook->getEvent() === 'saved') {
                $hook->execute($user, $data);
            }
        }

        return back()->with('success', __('builder::builder.account.profile_updated'));
    }

    private function makeDefinition(): AccountDefinition
    {
        return AccountDefinition::make(new AccountProfile, $this->registry->accountExtensions());
    }
}
