<?php

namespace PloverCRM\Core\Api\V1;

use PloverCRM\Common\LicenseChecker;
use PloverCRM\Core\Api\AbstractEndpoint;
use WP_REST_Request;

/**
 * License Endpoint
 *
 * POST /wp-json/plover-crm/v1/license/revoke
 */
class LicenseEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/license/(?P<action>revoke)';
    }

    public function getMethod()
    {
        return 'POST';
    }

    public function checkPermission(WP_REST_Request $request)
    {
        return true;
    }

    public function handle(WP_REST_Request $request)
    {
        $action = sanitize_key((string) $request->get_param('action'));

        if ($action !== 'revoke') {
            return $this->error('Unsupported license action.', 404, 'not_found');
        }

        $token = sanitize_text_field(
            $request->get_header('x-plovercrm-token') ?: (string) $request->get_param('token')
        );
        $timestamp = (int) (
            $request->get_header('x-plovercrm-timestamp') ?: $request->get_param('timestamp')
        );
        $signature = sanitize_text_field(
            $request->get_header('x-plovercrm-signature') ?: (string) $request->get_param('signature')
        );

        if ($token === '' || $timestamp <= 0 || $signature === '') {
            return $this->error('Token, timestamp, and signature are required.', 401, 'unauthorized');
        }

        if (!LicenseChecker::verifyHubRevokeSignature($token, $timestamp, $signature)) {
            return $this->error('Invalid or expired revoke signature.', 403, 'forbidden');
        }

        if (!LicenseChecker::revokeFromHub($token)) {
            return $this->error('License token does not match this site.', 404, 'license_not_found');
        }

        return $this->success([
            'revoked' => true,
            'message' => 'Local license revoked successfully.',
        ]);
    }
}
