<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Merchant;
use App\Support\ApiResponse;
use Illuminate\Auth\Events\Verified;
use Illuminate\Http\Request;

final class EmailVerificationController extends Controller
{
    public function notice(Request $request)
    {
        return ApiResponse::success(['verified' => $request->user()->hasVerifiedEmail()]);
    }

    public function send(Request $request)
    {
        if (! $request->user()->hasVerifiedEmail()) {
            $request->user()->sendEmailVerificationNotification();
        }

        return ApiResponse::success(['message' => 'Verification link sent.']);
    }

    public function verify(Request $request, string $id, string $hash)
    {
        $merchant = Merchant::findOrFail($id);

        abort_unless(hash_equals(sha1($merchant->getEmailForVerification()), $hash), 403);

        if (! $merchant->hasVerifiedEmail() && $merchant->markEmailAsVerified()) {
            event(new Verified($merchant));
        }

        return ApiResponse::success(['verified' => true]);
    }
}