<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Support\CheckoutRoutes;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\RedirectResponse;

class VerifyEmailController extends Controller
{
    /**
     * Mark the authenticated user's email address as verified.
     */
    public function __invoke(EmailVerificationRequest $request): RedirectResponse
    {
        if (! $request->user()->hasVerifiedEmail()) {
            $request->fulfill();
        }

        return $this->redirectAfterVerification($request);
    }

    protected function redirectAfterVerification(EmailVerificationRequest $request): RedirectResponse
    {
        $redirectToCheckout = $request->session()->pull('checkout.verify_redirect');
        $preferredLocale = $request->session()->get('preferred_locale');

        if (! $redirectToCheckout && $request->user()->pending_purchase) {
            $packageId = $request->session()->pull('checkout.pending_package_id');

            if (! $packageId) {
                $packageId = optional($request->user()->tenant)
                    ?->packages()
                    ->latest('tenant_packages.created_at')
                    ->value('packages.id');
            }

            if ($packageId) {
                $redirectToCheckout = CheckoutRoutes::wizardUrl($packageId, $preferredLocale);
            }
        }

        $this->flashVerificationSuccess($request, (bool) $redirectToCheckout);

        if ($redirectToCheckout) {
            $request->session()->forget('checkout.pending_package_id');
            $separator = str_contains($redirectToCheckout, '?') ? '&' : '?';

            return redirect()->to($redirectToCheckout.$separator.'verified=1');
        }

        $fallbackLogin = route('marketing.login');
        $separator = str_contains($fallbackLogin, '?') ? '&' : '?';

        return redirect()->intended($fallbackLogin.$separator.'verified=1');
    }

    private function flashVerificationSuccess(EmailVerificationRequest $request, bool $forCheckout): void
    {
        $message = $forCheckout
            ? __('auth.verification.checkout_success_message')
            : __('auth.verification.success_message');

        $request->session()->flash('verification', [
            'status' => 'success',
            'title' => __('auth.verification.success_title'),
            'message' => $message,
        ]);

        if (! $forCheckout) {
            $request->session()->flash('status', __('auth.verification.success_message'));
        }
    }
}
