<?php

namespace App\Services;

use App\Models\Visit;
use Illuminate\Support\Str;

class TokenService
{
    /**
     * Generate a unique registration token
     */
    public function generateRegistrationToken(): string
    {
        do {
            $token = Str::random(64);
        } while (Visit::where('registration_token', $token)->exists());

        return $token;
    }

    /**
     * Validate a registration token
     */
    public function validateToken(string $token): array
    {
        $visit = Visit::where('registration_token', $token)->first();

        if (!$visit) {
            return [
                'valid' => false,
                'error' => 'invalid',
                'message' => 'Registration token is invalid',
            ];
        }

        if ($visit->token_expires_at < now()) {
            return [
                'valid' => false,
                'error' => 'expired',
                'message' => 'Registration link has expired',
            ];
        }

        if ($visit->visitor_registered_at) {
            return [
                'valid' => false,
                'error' => 'already_used',
                'message' => 'This visit has already been registered',
            ];
        }

        return [
            'valid' => true,
            'visit' => $visit,
        ];
    }

    /**
     * Generate token expiration timestamp (7 days default)
     */
    public function getTokenExpiration(int $days = 7): \DateTime
    {
        return now()->addDays($days);
    }
}
