<?php

namespace Licenzo\Http\Controller\Api\V1;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

use Licenzo\Framework\Http\Request;
use Licenzo\Http\Traits\HandlesErrors;
use Licenzo\Services\QrCodeService;

class QrCodeController
{
    use HandlesErrors;

    private const ALLOWED_ENTITY_TYPES = ['license', 'subscription'];

    /**
     * Public verification endpoint — no auth required, rate-limited.
     * Validates the signed token and returns safe public status data.
     */
    public function verify(Request $request, $token): array
    {
        try {
            $token = sanitize_text_field((string) $token);

            $decoded = QrCodeService::verifyToken($token);
            if (!$decoded) {
                return $this->notFoundError('Invalid or expired verification link');
            }

            $statusData = QrCodeService::getStatusData($decoded['type'], $decoded['id']);
            if (!$statusData) {
                return $this->notFoundError('Invalid or expired verification link');
            }

            return $this->successResponse($statusData, 'Verification successful');
        } catch (\Throwable $e) {
            return $this->handleError($e, 'Verification failed');
        }
    }

    /**
     * Admin endpoint — generates a signed verification URL for a license or subscription.
     * The frontend renders the QR code using this URL with a JS library.
     */
    public function generateQr(Request $request): array
    {
        return [
            'success' => false,
            'message' => __('QR code verification is coming soon.', 'licenzo'),
            'status'  => 403,
        ];
    }
}
