<?php

declare(strict_types=1);

namespace Builder\Core\Http\Controllers\Auth;

use Builder\Core\Foundation\Middleware\BuilderAuth;
use Builder\Core\Http\Requests\Auth\InviteRequest;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;

final class StoreInviteController
{
    public function __invoke(InviteRequest $request, string $token): RedirectResponse
    {
        $guard = BuilderAuth::guard();

        $status = Password::broker('builder-invite')->reset(
            [
                'email' => $request->input('email'),
                'password' => $request->input('password'),
                'password_confirmation' => $request->input('password_confirmation'),
                'token' => $token,
            ],
            function (mixed $user, string $password) use ($guard): void {
                $user->forceFill([
                    'password' => Hash::make($password),
                    'activated_at' => now(),
                ])->save();

                event(new PasswordReset($user));
                Auth::guard($guard)->login($user);
            },
        );

        if ($status !== Password::PASSWORD_RESET) {
            return back()->withErrors(['email' => __('builder::builder.invite.invalid_token')]);
        }

        return redirect()->route('builder.dashboard')
            ->with('success', __('builder::builder.invite.password_set'));
    }
}
