<?php

namespace Modules\Auth\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Modules\Auth\Entities\User;
use Modules\Auth\Services\AuthSessionService;
use Modules\Auth\Services\EmailVerificationOtpService;

class EmailVerificationController extends Controller
{
    public function __construct(
        protected EmailVerificationOtpService $otpService,
        protected AuthSessionService $authSession
    ) {}

    public function verify(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'email' => ['required', 'string', 'email'],
            'otp' => ['required', 'string', 'digits:6'],
        ]);

        $user = User::where('email', $validated['email'])->first();

        if (! $user) {
            return response()->json([
                'success' => false,
                'message' => 'Kod OTP tidak sah.',
            ], 422);
        }

        $this->otpService->verify($user, $validated['otp']);

        $user->refresh();

        return $this->authSession->createAuthResponse(
            $user,
            'E-mel anda telah berjaya disahkan. Akaun anda sedang menunggu pengaktifan daripada pentadbir sistem.'
        );
    }

    public function resend(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'email' => ['required', 'string', 'email'],
        ]);

        $user = User::where('email', $validated['email'])->first();

        if ($user && ! $user->hasVerifiedEmail()) {
            $this->otpService->send($user);
        }

        return response()->json([
            'success' => true,
            'message' => 'Jika e-mel wujud dan belum disahkan, kod OTP baharu telah dihantar.',
        ]);
    }
}
