<?php

/**
 * REST API Routes
 *
 * @package Licenzo
 */

use Licenzo\Framework\Support\Facades\Route;

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

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your plugin. These
| routes are loaded by the ApiServiceProvider within a group which
| is assigned the "api" middleware group.
|
*/


// Admin Routes (Protected)
Route::group(['middleware' => ['auth'], 'policy' => \Licenzo\Policies\AdminPolicy::class], function () {

    // General Settings
    Route::get('/general-settings', [\Licenzo\Http\Controller\Api\V1\GeneralSettingsController::class, 'get'])->name('settings.general.get');
    Route::post('/general-settings', [\Licenzo\Http\Controller\Api\V1\GeneralSettingsController::class, 'update'])->name('settings.general.update');

    // Email Settings
    Route::get('/email-settings', [\Licenzo\Http\Controller\Api\V1\EmailSettingsController::class, 'get'])->name('settings.email.get');
    Route::post('/email-settings', [\Licenzo\Http\Controller\Api\V1\EmailSettingsController::class, 'update'])->name('settings.email.update');

    // Notification Settings
    Route::get('settings/email/notification', [\Licenzo\Http\Controller\Api\V1\EmailNotificationSettingController::class, 'get']);
    Route::post('settings/email/notification', [\Licenzo\Http\Controller\Api\V1\EmailNotificationSettingController::class, 'update']);

    // License Generator Settings
    Route::get('settings/license-generator', [\Licenzo\Http\Controller\Api\V1\LicenseGeneratorSettingsController::class, 'get']);
    Route::post('settings/license-generator', [\Licenzo\Http\Controller\Api\V1\LicenseGeneratorSettingsController::class, 'update']);

    // Subscription Settings
    Route::get('settings/subscription', [\Licenzo\Http\Controller\Api\V1\SubscriptionSettingsController::class, 'get']);
    Route::post('settings/subscription', [\Licenzo\Http\Controller\Api\V1\SubscriptionSettingsController::class, 'update']);
    Route::post('settings/plugin-dependencies/status', [\Licenzo\Http\Controller\Api\V1\SettingsPluginDependencyController::class, 'status']);
    Route::post('settings/plugin-dependencies/ensure', [\Licenzo\Http\Controller\Api\V1\SettingsPluginDependencyController::class, 'ensure']);


    // Route::post('/onboarding', [\Licenzo\Http\Controller\Api\V1\OnBoardingController::class, 'setup'])->name('onboarding.setup');

    Route::group(['prefix' => 'onboarding'], function () {
        Route::post('/', [\Licenzo\Http\Controller\Api\V1\OnBoardingController::class, 'setup'])->name('onboarding.setup');
        Route::get('/woocommerce-status', [\Licenzo\Http\Controller\Api\V1\OnBoardingController::class, 'woocommerceStatus'])->name('onboarding.woocommerce.status');
        Route::get('/woo-product-exist', [\Licenzo\Http\Controller\Api\V1\OnBoardingController::class, 'wooProductExist'])->name('onboarding.woo.product.exist');
    });

    // Dashboard Analytics
    Route::group(['prefix' => 'admin/dashboard'], function () {
        Route::get('/stats', [\Licenzo\Http\Controller\Api\V1\DashboardController::class, 'stats']);
        Route::get('/chart', [\Licenzo\Http\Controller\Api\V1\DashboardController::class, 'chartData']);
        Route::get('/subscription-overview', [\Licenzo\Http\Controller\Api\V1\DashboardController::class, 'subscriptionOverview']);
        Route::get('/license-usage', [\Licenzo\Http\Controller\Api\V1\DashboardController::class, 'licenseUsage']);
        Route::get('/recent-transactions', [\Licenzo\Http\Controller\Api\V1\DashboardController::class, 'recentTransactions']);
        Route::get('/recent-activity', [\Licenzo\Http\Controller\Api\V1\DashboardController::class, 'recentActivity']);
        Route::get('/top-products', [\Licenzo\Http\Controller\Api\V1\DashboardController::class, 'topProducts']);
    });


    // Products
    Route::group(['prefix' => 'admin/products'], function () {
        Route::get('/all', [\Licenzo\Http\Controller\Api\V1\ProductController::class, 'allProducts']);
        Route::get('/', [\Licenzo\Http\Controller\Api\V1\ProductController::class, 'index']);
        Route::post('/', [\Licenzo\Http\Controller\Api\V1\ProductController::class, 'store']);
        Route::get('/{productId}/releases', [\Licenzo\Http\Controller\Api\V1\ProductReleasesController::class, 'index']);
        Route::post('/{productId}/releases', [\Licenzo\Http\Controller\Api\V1\ProductReleasesController::class, 'store']);
        Route::get('/{productId}/releases/{releaseUuid}', [\Licenzo\Http\Controller\Api\V1\ProductReleasesController::class, 'show']);
        Route::put('/{productId}/releases/{releaseUuid}', [\Licenzo\Http\Controller\Api\V1\ProductReleasesController::class, 'update']);
        Route::delete('/{productId}/releases/{releaseUuid}', [\Licenzo\Http\Controller\Api\V1\ProductReleasesController::class, 'destroy']);
        Route::get('/{id}', [\Licenzo\Http\Controller\Api\V1\ProductController::class, 'show']);
        Route::put('/{id}', [\Licenzo\Http\Controller\Api\V1\ProductController::class, 'update']);
        Route::delete('/{id}', [\Licenzo\Http\Controller\Api\V1\ProductController::class, 'destroy']);

        // Product Dashboard
        Route::get('/{id}/stats', [\Licenzo\Http\Controller\Api\V1\ProductDashboardController::class, 'stats']);
        Route::get('/{id}/recent', [\Licenzo\Http\Controller\Api\V1\ProductDashboardController::class, 'recentRequests']);
        Route::get('/{id}/chart', [\Licenzo\Http\Controller\Api\V1\ProductDashboardController::class, 'chartData']);
    });

    // Customers
    Route::group(['prefix' => 'admin/customers'], function () {
        Route::get('/all', [\Licenzo\Http\Controller\Api\V1\CustomerController::class, 'allCustomers']);
        Route::get('/', [\Licenzo\Http\Controller\Api\V1\CustomerController::class, 'index']);
        Route::post('/', [\Licenzo\Http\Controller\Api\V1\CustomerController::class, 'store']);
        Route::get('/{id}', [\Licenzo\Http\Controller\Api\V1\CustomerController::class, 'show']);
        Route::put('/{id}', [\Licenzo\Http\Controller\Api\V1\CustomerController::class, 'update']);
        Route::delete('/{id}', [\Licenzo\Http\Controller\Api\V1\CustomerController::class, 'destroy']);

        Route::get('/{id}/subscriptions', [\Licenzo\Http\Controller\Api\V1\CustomerController::class, 'getCustomerSubscription']);
        Route::get('/{id}/licenses', [\Licenzo\Http\Controller\Api\V1\CustomerController::class, 'getCustomerLicense']);
        Route::get('/{id}/transactions', [\Licenzo\Http\Controller\Api\V1\CustomerController::class, 'getCustomerTransactions']);
        // Backward-compatible typo alias, kept for existing clients.
        Route::get('/{id}/transections', [\Licenzo\Http\Controller\Api\V1\CustomerController::class, 'getCustomerTransection']);
        Route::get('/{id}/products', [\Licenzo\Http\Controller\Api\V1\CustomerController::class, 'getCustomerProducts']);
    });

    // Licenses
    Route::group(['prefix' => 'admin/licenses'], function () {
        Route::get('/generate-key', [\Licenzo\Http\Controller\Api\V1\LicenseController::class, 'licenseGenerator']);
        Route::get('/', [\Licenzo\Http\Controller\Api\V1\LicenseController::class, 'index']);
        Route::post('/', [\Licenzo\Http\Controller\Api\V1\LicenseController::class, 'store']);
        Route::get('/{id}', [\Licenzo\Http\Controller\Api\V1\LicenseController::class, 'show']);
        Route::put('/{id}', [\Licenzo\Http\Controller\Api\V1\LicenseController::class, 'update']);
        Route::delete('/{id}', [\Licenzo\Http\Controller\Api\V1\LicenseController::class, 'destroy']);

        Route::put('/{license}/products/{licenseProduct}', [\Licenzo\Http\Controller\Api\V1\LicenseController::class, 'updateLicenseProduct']);
        Route::post('/generate-subscription-license', [\Licenzo\Http\Controller\Api\V1\LicenseController::class, 'generateSubscriptionLicense']);
        Route::post('/{id}/transfer', [\Licenzo\Http\Controller\Api\V1\LicenseController::class, 'transferLicense']);
    });

    // Subscriptions
    Route::group(['prefix' => 'admin/subscriptions'], function () {
        Route::get('/all', [\Licenzo\Http\Controller\Api\V1\SubscriptionController::class, 'allSubscriptions']);
        Route::get('/', [\Licenzo\Http\Controller\Api\V1\SubscriptionController::class, 'index']);
        Route::post('/', [\Licenzo\Http\Controller\Api\V1\SubscriptionController::class, 'store']);
        Route::get('/{id}', [\Licenzo\Http\Controller\Api\V1\SubscriptionController::class, 'show']);
        Route::put('/{id}', [\Licenzo\Http\Controller\Api\V1\SubscriptionController::class, 'update']);
        Route::delete('/{id}', [\Licenzo\Http\Controller\Api\V1\SubscriptionController::class, 'destroy']);

        Route::post('/{id}/pause', [\Licenzo\Http\Controller\Api\V1\SubscriptionController::class, 'pause']);
        Route::post('/{id}/resume', [\Licenzo\Http\Controller\Api\V1\SubscriptionController::class, 'resume']);
        Route::post('/{id}/cancel', [\Licenzo\Http\Controller\Api\V1\SubscriptionController::class, 'cancel']);

        Route::post('/{id}/transactions', [\Licenzo\Http\Controller\Api\V1\SubscriptionController::class, 'addTransaction']);

        // v1.0.0 parity stubs — route shapes frozen so third-party integrations
        // that polled these endpoints in 1.0.0 do not break on upgrade.
        // Both return the identical "coming soon" 403 payload the 1.0.0 stubs
        // returned. Do not wire real logic here; plan-change is out of scope
        // for v1.1.0 (ref: ADR-034, ADR-040).
        Route::post('/{id}/change-plan', [\Licenzo\Http\Controller\Api\V1\SubscriptionController::class, 'changePlan']);
        Route::post('/{id}/apply-pending-changes', [\Licenzo\Http\Controller\Api\V1\SubscriptionController::class, 'applyPendingChanges']);
    });


    // Providers
    Route::group(['prefix' => 'admin/providers'], function () {
        Route::get('/woo/users', [\Licenzo\Http\Controller\Api\V1\ProviderController::class, 'getWooUsers']);
        Route::get('/woo/products', [\Licenzo\Http\Controller\Api\V1\ProviderController::class, 'getWooProducts']);
        Route::get('/woo/orders', [\Licenzo\Http\Controller\Api\V1\ProviderController::class, 'getWooOrders']);
        Route::get('/edd/products', [\Licenzo\Http\Controller\Api\V1\ProviderController::class, 'getEddProducts']);
    });

    // QR Code Generation
    Route::post('/admin/qr/generate', [\Licenzo\Http\Controller\Api\V1\QrCodeController::class, 'generateQr']);

    // Data Export / Import
    Route::group(['prefix' => 'admin/tools'], function () {
        Route::get('/categories', [\Licenzo\Http\Controller\Api\V1\DataPortController::class, 'categories']);
        Route::get('/export', [\Licenzo\Http\Controller\Api\V1\DataPortController::class, 'export']);
        Route::post('/upload', [\Licenzo\Http\Controller\Api\V1\DataPortController::class, 'upload']);
        Route::post('/process', [\Licenzo\Http\Controller\Api\V1\DataPortController::class, 'process']);
    });
});

/*
|--------------------------------------------------------------------------
| Public Routes
|--------------------------------------------------------------------------
|
| Public routes are grouped by throttle policy so that each group's rate
| limit reflects its expected legitimate traffic profile:
|
|   throttle:activation  — lock/key operations (activation, validation,
|                          deactivation). Strict cap because a single
|                          site normally calls these a few times only.
|   throttle:public_read — read-ish endpoints called by installed sites
|                          on a cadence (update checks, QR verify,
|                          signed download redemption).
|   throttle:webhook     — high-volume legit traffic from payment
|                          gateways; cap is permissive but still
|                          bounded to resist gateway-spoofing floods.
|
| Policy definitions live in config/app.php under 'rate_limits'.
| Bucket-key derivation uses the MATCHED ROUTE TEMPLATE (not the raw
| URI), so per-license path segments collapse into a single bucket
| (see RateLimit::resolveRouteTemplate()).
|
*/

// Shared REST arg schemas (reused across the three public groups below).
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Closure-scoped via RouteServiceProvider::require().
$pathLicenseArgs = [
    'license'   => ['required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
    'product'   => ['required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
    'variation' => ['required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
];

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Closure-scoped via RouteServiceProvider::require().
$activationBodyArgs = [
    'instance_identifier' => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
    'activation_method'   => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
    'fingerprint'         => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
    'domain'              => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
];

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Closure-scoped via RouteServiceProvider::require().
$v2ActivationBodyArgs = [
    'instance_identifier' => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
    'site_url'            => ['type' => 'string', 'sanitize_callback' => 'esc_url_raw'],
    'home_url'            => ['type' => 'string', 'sanitize_callback' => 'esc_url_raw'],
];

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Closure-scoped via RouteServiceProvider::require().
$updateContextArgs = [
    'current_version'   => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
    'installed_version' => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
    'version'           => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
    'channel'           => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
    'site_url'          => ['type' => 'string', 'sanitize_callback' => 'esc_url_raw'],
    'home_url'          => ['type' => 'string', 'sanitize_callback' => 'esc_url_raw'],
    'plugin'            => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
    'slug'              => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
];

// Activation / validation / deactivation (lock/key operations)
Route::group(['middleware' => ['throttle:activation']], function () use ($pathLicenseArgs, $activationBodyArgs, $v2ActivationBodyArgs) {

    // License Activation (legacy — URL path parameters)
    Route::post('/activation/{license}/{product}/{variation}', [\Licenzo\Http\Controller\Api\V1\LicenseActivationController::class, 'activate'])
        ->args(array_merge($pathLicenseArgs, $activationBodyArgs));
    Route::post('/check/{license}/{product}/{variation}', [\Licenzo\Http\Controller\Api\V1\LicenseActivationController::class, 'check'])
        ->args(array_merge($pathLicenseArgs, [
            'instance_identifier' => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
            'activation_hash'     => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
        ]));
    Route::post('/deactivation/{license}/{product}/{variation}', [\Licenzo\Http\Controller\Api\V1\LicenseActivationController::class, 'deactivate'])
        ->args(array_merge($pathLicenseArgs, [
            'instance_identifier' => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
        ]));

    // License Activation (v2 — header-based credentials)
    Route::post('/activate', [\Licenzo\Http\Controller\Api\V1\ActivationController::class, 'activate'])
        ->args($v2ActivationBodyArgs);
    Route::post('/validate', [\Licenzo\Http\Controller\Api\V1\ActivationController::class, 'validate']);
    Route::post('/deactivate', [\Licenzo\Http\Controller\Api\V1\ActivationController::class, 'deactivate']);
});

// Update checks, info, signed download redemption, QR verify (public reads)
Route::group(['middleware' => ['throttle:public_read']], function () use ($pathLicenseArgs, $updateContextArgs) {

    // Product Updates (v2 — header-based credentials via activation token)
    Route::post('/updates/check', [\Licenzo\Http\Controller\Api\V1\ActivationController::class, 'updateCheck'])
        ->args($updateContextArgs);
    Route::post('/updates/info', [\Licenzo\Http\Controller\Api\V1\ActivationController::class, 'updateInfo'])
        ->args($updateContextArgs);

    // Product Updates (legacy — URL path parameters)
    Route::get('/updates/check/{license}/{product}/{variation}', [\Licenzo\Http\Controller\Api\V1\ProductUpdatesController::class, 'check'])
        ->args(array_merge($pathLicenseArgs, $updateContextArgs));
    Route::post('/updates/check/{license}/{product}/{variation}', [\Licenzo\Http\Controller\Api\V1\ProductUpdatesController::class, 'check'])
        ->args(array_merge($pathLicenseArgs, $updateContextArgs));
    Route::get('/updates/info/{license}/{product}/{variation}', [\Licenzo\Http\Controller\Api\V1\ProductUpdatesController::class, 'info'])
        ->args(array_merge($pathLicenseArgs, $updateContextArgs));
    Route::post('/updates/info/{license}/{product}/{variation}', [\Licenzo\Http\Controller\Api\V1\ProductUpdatesController::class, 'info'])
        ->args(array_merge($pathLicenseArgs, $updateContextArgs));
    Route::get('/updates/download/{token}', [\Licenzo\Http\Controller\Api\V1\ProductUpdatesController::class, 'download'])
        ->args([
            'token' => ['required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
        ]);

    // QR code public verification
    Route::get('/verify/{token}', [\Licenzo\Http\Controller\Api\V1\QrCodeController::class, 'verify'])
        ->args([
            'token' => ['required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field'],
        ]);
});

// Customer portal routes (cookie-authenticated, no throttle — admin-style rate ceiling)
Route::group(['prefix' => 'customer', 'middleware' => ['customer_auth']], function () {
    Route::get('/overview', [\Licenzo\Http\Controller\Api\V1\Customers\CustomerController::class, 'overview']);
    Route::get('/licenses', [\Licenzo\Http\Controller\Api\V1\Customers\CustomerController::class, 'licenses']);
    Route::get('/subscriptions', [\Licenzo\Http\Controller\Api\V1\Customers\CustomerController::class, 'subscriptions']);
    Route::get('/downloads', [\Licenzo\Http\Controller\Api\V1\Customers\CustomerController::class, 'downloads']);

    // License activations
    Route::get('/licenses/{licenseId}/activations', [\Licenzo\Http\Controller\Api\V1\Customers\CustomerController::class, 'licenseActivations']);
    Route::post('/licenses/{licenseId}/activations/{activationId}/deactivate', [\Licenzo\Http\Controller\Api\V1\Customers\CustomerController::class, 'deactivateActivation']);

    // Subscription management
    Route::post('/subscriptions/{subscriptionId}/cancel', [\Licenzo\Http\Controller\Api\V1\Customers\CustomerController::class, 'cancelSubscription']);

    // Authenticated file download
    Route::get('/downloads/{productId}/{variationId}/file', [\Licenzo\Http\Controller\Api\V1\Customers\CustomerController::class, 'downloadFile']);
});

// Webhook ingestion (public, signed, high-volume from gateways)
Route::group(['middleware' => ['throttle:webhook']], function () {
    Route::post('/webhooks/woocommerce', [\Licenzo\Http\Controller\Api\V1\WebhookController::class, 'woocommerce']);
    Route::post('/webhooks/stripe', [\Licenzo\Http\Controller\Api\V1\StripeWebhookController::class, 'handle']);
});
