<?php

namespace Modules\Auth\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Verified;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
use Modules\Auth\Entities\User;

class EmailVerificationController extends Controller
{
    public function verify(Request $request, string $id, string $hash): RedirectResponse
    {
        if (! URL::hasValidSignature($request)) {
            return $this->redirectToFrontend('invalid');
        }

        $user = User::find($id);

        if (! $user || ! hash_equals($hash, sha1($user->getEmailForVerification()))) {
            return $this->redirectToFrontend('invalid');
        }

        if ($user->hasVerifiedEmail()) {
            return $this->redirectToFrontend('already');
        }

        $user->markEmailAsVerified();

        event(new Verified($user));

        return $this->redirectToFrontend('success', $user);
    }

    public function send(Request $request): JsonResponse
    {
        $user = $request->user();

        if ($user->hasVerifiedEmail()) {
            return response()->json([
                'success' => true,
                'message' => 'E-mel anda telah disahkan.',
            ]);
        }

        $user->sendEmailVerificationNotification();

        return response()->json([
            'success' => true,
            'message' => 'Pautan pengesahan e-mel telah dihantar.',
        ]);
    }

    protected function redirectToFrontend(string $status, ?User $user = null): RedirectResponse
    {
        $baseUrl = rtrim(config('user.frontend_url'), '/');
        $path = config('auth.verification.frontend_redirect_path', '/profile');

        if ($user?->status === 'pending') {
            $path = '/register?registered=success';
        }

        return redirect()->away("{$baseUrl}{$path}?verified={$status}");
    }
}
