<?php
namespace Formipay;
use Formipay\Traits\SingletonTrait;

if ( ! defined( 'ABSPATH' ) ) exit;

class LicenseAPI {
    use SingletonTrait;

    protected function __construct() {
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    public function register_routes() {
        $ns = 'formipay/v1';
        register_rest_route($ns, '/license/verify', [
            'methods'  => 'POST',
            'callback' => [$this, 'verify'],
            'permission_callback' => '__return_true',
        ]);
        register_rest_route($ns, '/license/activate', [
            'methods'  => 'POST',
            'callback' => [$this, 'activate'],
            'permission_callback' => '__return_true',
        ]);
        register_rest_route($ns, '/license/deactivate', [
            'methods'  => 'POST',
            'callback' => [$this, 'deactivate'],
            'permission_callback' => '__return_true',
        ]);
        register_rest_route($ns, '/license/revoke', [
            'methods'  => 'POST',
            'callback' => [$this, 'revoke'],
            'permission_callback' => [$this, 'revoke_permission'], // optional secret protection
        ]);
    }

    // === Handlers (stubs) ===

    public function verify(\WP_REST_Request $req) {
        // TODO: rate-limit, load by (key, form_id), compute effective status, return JSON
        return new \WP_REST_Response(['ok' => true, 'status' => 'active']);
    }

    public function activate(\WP_REST_Request $req) {
        // TODO: validate, idempotent per device_id, enforce max, update meta_data.activations
        return new \WP_REST_Response(['ok' => true]);
    }

    public function deactivate(\WP_REST_Request $req) {
        // TODO: remove device, idempotent
        return new \WP_REST_Response(['ok' => true]);
    }

    public function revoke(\WP_REST_Request $req) {
        // TODO: optional header check, set status=revoked
        return new \WP_REST_Response(['ok' => true, 'status' => 'revoked']);
    }

    public function revoke_permission(\WP_REST_Request $req) {
        // TODO: if you want to protect revoke via an option-stored secret
        return true; // or false
    }

    // === Helpers (signatures only) ===

    private function rate_limit_ok() { /* TODO */ return true; }
    private function load_license($key, $form_id) { /* TODO */ return null; }
    private function effective_status($row) { /* TODO */ return 'active'; }
    private function update_activations($row, $device_id, $op = 'add', $meta = []) { /* TODO */ return $row; }
}