<?php

declare(strict_types=1);

namespace Builder\Core\Http\Controllers\Auth;

use Illuminate\Auth\Passwords\PasswordBroker;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Inertia\Inertia;
use Inertia\Response;

final class ShowInviteController
{
    public function __invoke(Request $request, string $token): Response|RedirectResponse
    {
        $email = (string) $request->query('email', '');

        /** @var PasswordBroker $broker */
        $broker = Password::broker('builder-invite');

        $user = $broker->getUser(['email' => $email]);

        if ($user === null || ! $broker->tokenExists($user, $token)) {
            return redirect()->route('builder.login')
                ->with('error', __('builder::builder.invite.invalid_token'));
        }

        return Inertia::render('Auth/AcceptInvite', [
            'token' => $token,
            'email' => $email,
        ]);
    }
}
