<?php

namespace Modules\Auth\Actions\Fortify;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Laravel\Fortify\Contracts\LoginResponse as ContractsLoginResponse;
use Modules\Auth\Services\AuthSessionService;
use Modules\Auth\Services\EmailVerificationOtpService;

class LoginResponse implements ContractsLoginResponse
{
    public function __construct(
        protected AuthSessionService $authSession,
        protected EmailVerificationOtpService $otpService,
    ) {}

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

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

            Auth::guard(config('fortify.guard'))->logout();

            return response()->json([
                'success' => true,
                'message' => 'Sila semak e-mel anda untuk kod pengesahan 6 digit.',
                'data' => [
                    'email' => $user->email,
                    'requires_email_verification' => true,
                ],
            ]);
        }

        return $this->authSession->createAuthResponse(
            $user,
            'Login successful'
        );
    }
}
