<?php

namespace App\Http\Responses;

use App\Http\Controllers\InviteController;
use Laravel\Fortify\Contracts\RegisterResponse as RegisterResponseContract;
use Symfony\Component\HttpFoundation\Response;

class RegisterResponse implements RegisterResponseContract
{
    public function toResponse($request): Response
    {
        $reqId = substr(bin2hex(random_bytes(4)), 0, 8);
        $start = microtime(true);
        $stamp = function (string $msg) use ($reqId, $start) {
            $elapsedMs = (int) ((microtime(true) - $start) * 1000);
            \Illuminate\Support\Facades\Log::info("[RegFlow] req={$reqId} +{$elapsedMs}ms RegisterResponse {$msg}");
        };

        $stamp('ENTER');
        $user = \Illuminate\Support\Facades\Auth::user();
        $stamp('Auth::user() resolved id=' . ($user?->id ?? 'NULL') . ' email=' . ($user?->email ?? 'NULL') . ' session_id=' . session()->getId());

        // If the user just registered after clicking a workspace invite
        // link, the token is sitting in the session. Hand it off to the
        // invite controller so they're added to the inviting workspace.
        $stamp('STEP invite check about to run');
        $inviteRedirect = InviteController::processPendingInvite($user);
        if ($inviteRedirect) {
            $stamp('EXIT redirecting via invite path');
            return $inviteRedirect;
        }
        $stamp('OK no pending invite');

        // No pending invite — fall back to the same destination logic
        // LoginResponse uses for ordinary signups.
        //
        // Verification gate (anti-spam mode): when the admin has flipped
        // "Require email verification" ON, brand-new users get routed to
        // /email/verify FIRST. They sit on the "we sent you a link" page
        // until they click the email link; Fortify's VerifyEmailController
        // then marks them verified and redirects to
        // fortify.redirects.email-verification (= /onboarding/step-1),
        // so the post-verify landing is the same as the friction-free
        // path below — only the order changes.
        //
        // When the toggle is OFF, User::sendEmailVerificationNotification()
        // has already auto-marked the user verified, so this branch is
        // skipped and we go straight to the destination picker — exact
        // behavior the platform shipped with.
        $stamp('STEP verification gate check');
        $verificationRequired = \App\Models\SystemSetting::get(
            'require_email_verification',
            'true',
        ) === 'true';

        if ($verificationRequired
            && $user
            && !$user->is_admin
            && method_exists($user, 'hasVerifiedEmail')
            && !$user->hasVerifiedEmail()
        ) {
            $stamp('EXIT verification required, redirecting to /email/verify');
            return redirect()->route('verification.notice');
        }

        $stamp('STEP destination picker');
        if ($user->is_admin) {
            $home = url('/admin/dashboard');
            $branch = 'is_admin';
        } elseif (! $user->hasWorkspace()) {
            $home = url('/onboarding/step-1');
            $branch = 'no-workspace';
        } else {
            $home = url('/dashboard');
            $branch = 'has-workspace';
        }
        $stamp("OK picked branch={$branch} home={$home}");

        if ($request->wantsJson()) {
            $stamp('EXIT json response');
            return response()->json(['redirect' => $home]);
        }

        $stamp('EXIT 302 redirect ' . $home);
        return redirect($home);
    }
}
