<?php

namespace App\Services;

use App\Models\User;
use App\Models\Verification;
use Illuminate\Support\Facades\URL;

class VerificationService
{
    public static function create(User $user, string $type = 'email'): Verification
    {
        $verification = Verification::where('user_id', $user->id)
            ->where('type', $type)
            ->whereNull('verified_at')
            ->latest()
            ->first();

        if ($verification) {

            // 🔥 UPDATE statt DELETE
            $verification->update([
                'code' => rand(100000, 999999),
                'expires_at' => now()->addMinutes(10),
            ]);

        } else {

            $verification = Verification::create([
                'user_id' => $user->id,
                'type' => $type,
                'channel' => 'email',
                'code' => rand(100000, 999999),
                'expires_at' => now()->addMinutes(10),
            ]);
        }

        // 🔥 URL
        $url = URL::temporarySignedRoute(
            'verify.user',
            $verification->expires_at,
            [
                'verification' => $verification->id
            ]
        );

        MailService::queue(
            $user->email,
            'auth.verify',
            [
                'user' => $user->name,
                'url' => $url,
            ],
            $user->locale,
            null,
            $user->id
        );

        return $verification;
    }


    public static function verify(User $user, string $code, string $type = 'email'): bool
    {
        $verification = Verification::where('user_id', $user->id)
            ->where('type', $type)
            ->latest()
            ->first();

        if (!$verification) return false;
        if ($verification->isExpired()) return false;
        if ($verification->code !== $code) return false;

        $verification->update([
            'verified_at' => now(),
        ]);

        if ($type === 'email') {
            $user->update([
                'email_verified_at' => now(),
            ]);
        }

        return true;
    }
}
