<?php

use App\Http\Controllers\Api;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::prefix('v1')->group(function () {

    // ── Public auth (no token required) ──────────────────────────────
    Route::prefix('auth')->middleware('throttle:api')->group(function () {
        Route::post('register',         [Api\AuthController::class, 'register'])->middleware('throttle:sensitive');
        Route::post('login',            [Api\AuthController::class, 'login']);

        // Email-link reset (kept for backwards compat with web)
        Route::post('forgot-password',  [Api\AuthController::class, 'forgotPassword'])->middleware('throttle:sensitive');
        Route::post('reset-password',   [Api\AuthController::class, 'resetPassword'])->middleware('throttle:sensitive');

        // OTP-based reset (mobile preferred)
        Route::post('forgot-password/send-otp',   [Api\AuthController::class, 'forgotPasswordSendOtp'])->middleware('throttle:sensitive');
        Route::post('forgot-password/verify-otp', [Api\AuthController::class, 'forgotPasswordVerifyOtp'])->middleware('throttle:sensitive');
        Route::post('forgot-password/reset',      [Api\AuthController::class, 'forgotPasswordResetWithOtp'])->middleware('throttle:sensitive');

        Route::post('social/{provider}', [Api\AuthController::class, 'socialLogin'])
            ->where('provider', 'google|microsoft|github|facebook')
            ->middleware('throttle:sensitive');
    });

    // ── Auth — endpoints that require a Sanctum token ────────────────
    Route::prefix('auth')->middleware(['auth:sanctum', 'throttle:api'])->group(function () {
        Route::post('logout', [Api\AuthController::class, 'logout']);
        Route::get('me',      [Api\AuthController::class, 'me']);
        Route::get('profile', [Api\AuthController::class, 'profile']);

        // Profile management — single endpoint for name/email/phone/image/etc.
        Route::put('profile',           [Api\AuthController::class, 'updateProfile']);
        Route::post('profile',          [Api\AuthController::class, 'updateProfile']);
        Route::post('change-password',  [Api\AuthController::class, 'changePassword'])->middleware('throttle:sensitive');

        // Two-factor authentication — TOTP (Google Authenticator)
        Route::post('2fa/setup',   [Api\AuthController::class, 'twoFactorSetup'])->middleware('throttle:sensitive');
        Route::post('2fa/confirm', [Api\AuthController::class, 'twoFactorConfirm'])->middleware('throttle:sensitive');
        Route::post('2fa/disable', [Api\AuthController::class, 'twoFactorDisable'])->middleware('throttle:sensitive');

        // Two-factor authentication — PIN (mobile-friendly alternative)
        Route::post('2fa/pin/setup',  [Api\AuthController::class, 'twoFactorSetupPin'])->middleware('throttle:sensitive');
        Route::post('2fa/pin/change', [Api\AuthController::class, 'twoFactorChangePin'])->middleware('throttle:sensitive');

        // Recovery codes — works for both methods
        Route::post('2fa/recovery-codes/regenerate', [Api\AuthController::class, 'twoFactorRegenerateRecoveryCodes'])->middleware('throttle:sensitive');
    });

    // ── Mobile app endpoints — bearer-token auth, scoped to active workspace ──
    Route::prefix('mobile')->middleware(['auth:sanctum', 'throttle:api'])->group(function () {
        // Inbox
        Route::get(   'inbox/conversations',                  [\App\Http\Controllers\Api\Mobile\InboxController::class, 'index']);
        Route::get(   'inbox/conversations/{id}',             [\App\Http\Controllers\Api\Mobile\InboxController::class, 'show'])->whereNumber('id');
        Route::post(  'inbox/conversations/{id}/reply',       [\App\Http\Controllers\Api\Mobile\InboxController::class, 'reply'])->whereNumber('id')->middleware('throttle:sensitive');
        Route::post(  'inbox/conversations/{id}/action',      [\App\Http\Controllers\Api\Mobile\InboxController::class, 'action'])->whereNumber('id');
        Route::post(  'inbox/conversations/{id}/summarize',   [\App\Http\Controllers\Api\Mobile\InboxController::class, 'summarize'])->whereNumber('id')->middleware('throttle:sensitive');

        // Bin / Trash lifecycle — dedicated routes so the Flutter app
        // doesn't have to body-encode `{"action":"restore"}` through the
        // generic /action endpoint for what is the single most common
        // operation in the Bin folder. Bulk-restore + empty-trash mirror
        // the multi-select bottom-sheet on the mobile Bin screen.
        Route::post(  'inbox/conversations/{id}/restore',     [\App\Http\Controllers\Api\Mobile\InboxController::class, 'restore'])->whereNumber('id');
        Route::post(  'inbox/conversations/restore',          [\App\Http\Controllers\Api\Mobile\InboxController::class, 'restoreBulk']);
        Route::delete('inbox/conversations/trash',            [\App\Http\Controllers\Api\Mobile\InboxController::class, 'emptyTrash']);
        Route::post(  'inbox/messages/{messageId}/forward',   [\App\Http\Controllers\Api\Mobile\InboxController::class, 'forward'])->whereNumber('messageId')->middleware('throttle:sensitive');
        Route::post(  'inbox/compose',                        [\App\Http\Controllers\Api\Mobile\InboxController::class, 'compose'])->middleware('throttle:sensitive');
        Route::get(   'inbox/sidebar',                        [\App\Http\Controllers\Api\Mobile\InboxController::class, 'sidebar']);
        Route::get(   'inbox/accounts',                       [\App\Http\Controllers\Api\Mobile\InboxController::class, 'accounts']);

        // Inbox Drafts — list / fetch / update / delete / send for
        // outbound messages saved via compose `save_as_draft=true`. The
        // create-from-scratch path is still POST /inbox/compose with
        // save_as_draft=true; these routes cover the rest of the lifecycle.
        Route::get(   'inbox/drafts',                         [\App\Http\Controllers\Api\Mobile\InboxDraftsController::class, 'index']);
        Route::get(   'inbox/drafts/{id}',                    [\App\Http\Controllers\Api\Mobile\InboxDraftsController::class, 'show'])->whereNumber('id');
        Route::put(   'inbox/drafts/{id}',                    [\App\Http\Controllers\Api\Mobile\InboxDraftsController::class, 'update'])->whereNumber('id');
        Route::delete('inbox/drafts/{id}',                    [\App\Http\Controllers\Api\Mobile\InboxDraftsController::class, 'destroy'])->whereNumber('id');
        Route::post(  'inbox/drafts/{id}/send',               [\App\Http\Controllers\Api\Mobile\InboxDraftsController::class, 'send'])->whereNumber('id')->middleware('throttle:sensitive');

        // Quick Replies — inbox snippet manager (canned_responses table)
        Route::get(   'quick-replies',                        [\App\Http\Controllers\Api\Mobile\QuickRepliesController::class, 'index']);
        Route::post(  'quick-replies',                        [\App\Http\Controllers\Api\Mobile\QuickRepliesController::class, 'store']);
        Route::get(   'quick-replies/{id}',                   [\App\Http\Controllers\Api\Mobile\QuickRepliesController::class, 'show'])->whereNumber('id');
        Route::put(   'quick-replies/{id}',                   [\App\Http\Controllers\Api\Mobile\QuickRepliesController::class, 'update'])->whereNumber('id');
        Route::delete('quick-replies/{id}',                   [\App\Http\Controllers\Api\Mobile\QuickRepliesController::class, 'destroy'])->whereNumber('id');
        Route::post(  'quick-replies/{id}/insert',            [\App\Http\Controllers\Api\Mobile\QuickRepliesController::class, 'insert'])->whereNumber('id');

        // Contacts — autocomplete + frequent for compose screen
        Route::get( 'contacts/search',                      [\App\Http\Controllers\Api\Mobile\ContactsController::class, 'search']);
        Route::get( 'contacts/frequent',                    [\App\Http\Controllers\Api\Mobile\ContactsController::class, 'frequent']);

        // Contacts — Contacts tab (list + detail + CRUD + actions)
        Route::get(   'contacts',                           [\App\Http\Controllers\Api\Mobile\ContactsController::class, 'index']);
        Route::post(  'contacts',                           [\App\Http\Controllers\Api\Mobile\ContactsController::class, 'store'])->middleware('throttle:sensitive');
        Route::get(   'contacts/{id}',                      [\App\Http\Controllers\Api\Mobile\ContactsController::class, 'show'])->whereNumber('id');
        Route::put(   'contacts/{id}',                      [\App\Http\Controllers\Api\Mobile\ContactsController::class, 'update'])->whereNumber('id');
        Route::delete('contacts/{id}',                      [\App\Http\Controllers\Api\Mobile\ContactsController::class, 'destroy'])->whereNumber('id');
        Route::post(  'contacts/{id}/action',               [\App\Http\Controllers\Api\Mobile\ContactsController::class, 'action'])->whereNumber('id');

        // Workspaces — list / detail / create / update / switch active.
        // The "switch" route is what controls every other mobile request's
        // scope: `active_workspace_id` is read on every authenticated
        // call, so flipping it server-side switches what `index`-style
        // endpoints return on the next request.
        Route::get(   'workspaces',                         [\App\Http\Controllers\Api\Mobile\WorkspacesController::class, 'index']);
        Route::post(  'workspaces',                         [\App\Http\Controllers\Api\Mobile\WorkspacesController::class, 'store'])->middleware('throttle:sensitive');
        Route::get(   'workspaces/{id}',                    [\App\Http\Controllers\Api\Mobile\WorkspacesController::class, 'show'])->whereNumber('id');
        Route::put(   'workspaces/{id}',                    [\App\Http\Controllers\Api\Mobile\WorkspacesController::class, 'update'])->whereNumber('id');
        Route::delete('workspaces/{id}',                    [\App\Http\Controllers\Api\Mobile\WorkspacesController::class, 'destroy'])->whereNumber('id')->middleware('throttle:sensitive');
        Route::post(  'workspaces/{id}/switch',             [\App\Http\Controllers\Api\Mobile\WorkspacesController::class, 'switchActive'])->whereNumber('id');

        // Campaigns — list / create / detail / update / send / test / delete.
        // Send routes go through the shared CampaignService so SMS and
        // email both benefit from the same audience expansion, batching
        // and delivery-status accounting as the web app.
        Route::get(   'campaigns',                          [\App\Http\Controllers\Api\Mobile\CampaignsController::class, 'index']);
        Route::post(  'campaigns',                          [\App\Http\Controllers\Api\Mobile\CampaignsController::class, 'store'])->middleware('throttle:sensitive');
        Route::get(   'campaigns/{id}',                     [\App\Http\Controllers\Api\Mobile\CampaignsController::class, 'show'])->whereNumber('id');
        Route::put(   'campaigns/{id}',                     [\App\Http\Controllers\Api\Mobile\CampaignsController::class, 'update'])->whereNumber('id');
        Route::post(  'campaigns/{id}/send',                [\App\Http\Controllers\Api\Mobile\CampaignsController::class, 'send'])->whereNumber('id')->middleware('throttle:sensitive');
        Route::post(  'campaigns/{id}/test',                [\App\Http\Controllers\Api\Mobile\CampaignsController::class, 'sendTest'])->whereNumber('id')->middleware('throttle:sensitive');
        Route::delete('campaigns/{id}',                     [\App\Http\Controllers\Api\Mobile\CampaignsController::class, 'destroy'])->whereNumber('id');

        // Campaign attachments — Flutter uploads files (PDF/image/ZIP/…)
        // while editing a draft. SendCampaignEmailJob copies each file
        // into every outgoing email at send time.
        Route::get(   'campaigns/{id}/attachments',                       [\App\Http\Controllers\Api\Mobile\CampaignAttachmentsController::class, 'index'])->whereNumber('id');
        Route::post(  'campaigns/{id}/attachments',                       [\App\Http\Controllers\Api\Mobile\CampaignAttachmentsController::class, 'store'])->whereNumber('id')->middleware('throttle:sensitive');
        Route::delete('campaigns/{id}/attachments/{attachmentId}',        [\App\Http\Controllers\Api\Mobile\CampaignAttachmentsController::class, 'destroy'])->whereNumber('id')->whereNumber('attachmentId');

        // AB test variants — list / replace all / update one / delete one
        // / manual winner. {variant} is routed by letter ('A','B',…) so
        // the Flutter UI doesn't have to keep an id→letter map.
        Route::get(   'campaigns/{id}/variants',                          [\App\Http\Controllers\Api\Mobile\CampaignVariantsController::class, 'index'])->whereNumber('id');
        Route::post(  'campaigns/{id}/variants',                          [\App\Http\Controllers\Api\Mobile\CampaignVariantsController::class, 'replace'])->whereNumber('id');
        Route::put(   'campaigns/{id}/variants/{variant}',                [\App\Http\Controllers\Api\Mobile\CampaignVariantsController::class, 'update'])->whereNumber('id')->where('variant', '[A-Za-z0-9]{1,5}');
        Route::delete('campaigns/{id}/variants/{variant}',                [\App\Http\Controllers\Api\Mobile\CampaignVariantsController::class, 'destroy'])->whereNumber('id')->where('variant', '[A-Za-z0-9]{1,5}');
        Route::post(  'campaigns/{id}/variants/{variant}/winner',         [\App\Http\Controllers\Api\Mobile\CampaignVariantsController::class, 'markWinner'])->whereNumber('id')->where('variant', '[A-Za-z0-9]{1,5}');

        // Audience selectors — populates the composer's "Send to:"
        // dropdown. options() returns everything in one round-trip;
        // count() recomputes recipient count for the chosen audience.
        Route::get(   'campaigns/audience/options',                       [\App\Http\Controllers\Api\Mobile\CampaignAudienceController::class, 'options']);
        Route::get(   'campaigns/audience/count',                         [\App\Http\Controllers\Api\Mobile\CampaignAudienceController::class, 'count']);
        Route::get(   'campaigns/audience/lists',                         [\App\Http\Controllers\Api\Mobile\CampaignAudienceController::class, 'lists']);
        Route::get(   'campaigns/audience/segments',                      [\App\Http\Controllers\Api\Mobile\CampaignAudienceController::class, 'segments']);

        // Email templates the composer can fork from. Returns both
        // workspace-owned and platform-default templates.
        Route::get(   'email-templates',                                  [\App\Http\Controllers\Api\Mobile\EmailTemplatesController::class, 'index']);
        Route::get(   'email-templates/{id}',                             [\App\Http\Controllers\Api\Mobile\EmailTemplatesController::class, 'show'])->whereNumber('id');
        Route::post(  'email-templates/{id}/use',                         [\App\Http\Controllers\Api\Mobile\EmailTemplatesController::class, 'recordUse'])->whereNumber('id');

        // Notifications — bell screen
        Route::get(   'notifications',                      [\App\Http\Controllers\Api\Mobile\NotificationsController::class, 'index']);
        Route::post(  'notifications/read-all',             [\App\Http\Controllers\Api\Mobile\NotificationsController::class, 'markAllRead']);
        Route::post(  'notifications/{id}/read',            [\App\Http\Controllers\Api\Mobile\NotificationsController::class, 'markRead']);
        Route::delete('notifications/{id}',                 [\App\Http\Controllers\Api\Mobile\NotificationsController::class, 'destroy']);

        // Insights dashboard
        Route::get(   'insights',                           [\App\Http\Controllers\Api\Mobile\InsightsController::class, 'show']);

        // Settings / profile summary
        Route::get(   'settings',                           [\App\Http\Controllers\Api\Mobile\SettingsController::class, 'show']);

        // Privacy & Data — GDPR controls
        Route::get(   'privacy',                            [\App\Http\Controllers\Api\Mobile\PrivacyController::class, 'show']);
        Route::put(   'privacy',                            [\App\Http\Controllers\Api\Mobile\PrivacyController::class, 'update']);
        Route::post(  'privacy/export',                     [\App\Http\Controllers\Api\Mobile\PrivacyController::class, 'export'])->middleware('throttle:sensitive');
        Route::post(  'privacy/deletion-request',           [\App\Http\Controllers\Api\Mobile\PrivacyController::class, 'requestDeletion'])->middleware('throttle:sensitive');
        Route::post(  'privacy/deletion-cancel',            [\App\Http\Controllers\Api\Mobile\PrivacyController::class, 'cancelDeletion']);
        Route::post(  'privacy/deactivate',                 [\App\Http\Controllers\Api\Mobile\PrivacyController::class, 'deactivate'])->middleware('throttle:sensitive');

        // Billing & invoices
        Route::get(   'billing',                            [\App\Http\Controllers\Api\Mobile\BillingController::class, 'show']);
        Route::get(   'billing/invoices',                   [\App\Http\Controllers\Api\Mobile\BillingController::class, 'invoices']);
        Route::get(   'billing/invoices/{id}/download',     [\App\Http\Controllers\Api\Mobile\BillingController::class, 'downloadInvoice'])->whereNumber('id');
        Route::get(   'billing/portal',                     [\App\Http\Controllers\Api\Mobile\BillingController::class, 'portal']);
        Route::post(  'billing/upgrade',                    [\App\Http\Controllers\Api\Mobile\BillingController::class, 'upgrade'])->middleware('throttle:sensitive');

        // Team members + invites
        Route::get(   'team',                               [\App\Http\Controllers\Api\Mobile\TeamController::class, 'index']);
        Route::post(  'team/invites',                       [\App\Http\Controllers\Api\Mobile\TeamController::class, 'invite'])->middleware('throttle:sensitive');
        Route::post(  'team/invites/{id}/resend',           [\App\Http\Controllers\Api\Mobile\TeamController::class, 'resendInvite'])->whereNumber('id')->middleware('throttle:sensitive');
        Route::delete('team/invites/{id}',                  [\App\Http\Controllers\Api\Mobile\TeamController::class, 'cancelInvite'])->whereNumber('id');
        Route::put(   'team/members/{userId}',              [\App\Http\Controllers\Api\Mobile\TeamController::class, 'updateMember'])->whereNumber('userId');
        Route::delete('team/members/{userId}',              [\App\Http\Controllers\Api\Mobile\TeamController::class, 'removeMember'])->whereNumber('userId');

        // Email accounts — list / add (IMAP or OAuth) / edit / disconnect
        Route::get(   'email-accounts',                     [\App\Http\Controllers\Api\Mobile\EmailAccountsController::class, 'index']);
        Route::get(   'email-accounts/providers',           [\App\Http\Controllers\Api\Mobile\EmailAccountsController::class, 'providers']);
        Route::post(  'email-accounts',                     [\App\Http\Controllers\Api\Mobile\EmailAccountsController::class, 'store'])->middleware('throttle:sensitive');
        Route::post(  'email-accounts/test-connection',     [\App\Http\Controllers\Api\Mobile\EmailAccountsController::class, 'testConnection'])->middleware('throttle:sensitive');
        Route::post(  'email-accounts/oauth/{provider}',          [\App\Http\Controllers\Api\Mobile\EmailAccountsController::class, 'startOAuth'])->middleware('throttle:sensitive');
        Route::post(  'email-accounts/oauth/{provider}/exchange', [\App\Http\Controllers\Api\Mobile\EmailAccountsController::class, 'exchangeOAuth'])->middleware('throttle:sensitive');
        Route::get(   'email-accounts/{id}',                [\App\Http\Controllers\Api\Mobile\EmailAccountsController::class, 'show'])->whereNumber('id');
        Route::put(   'email-accounts/{id}',                [\App\Http\Controllers\Api\Mobile\EmailAccountsController::class, 'update'])->whereNumber('id');
        Route::delete('email-accounts/{id}',                [\App\Http\Controllers\Api\Mobile\EmailAccountsController::class, 'destroy'])->whereNumber('id');

        // Push notification device registration (FCM / APNs).
        // Mobile app calls POST /devices on sign-in + after token refresh,
        // DELETE on sign-out so the row no longer routes pushes.
        Route::post(  'devices',                            [\App\Http\Controllers\Api\Mobile\DevicesController::class, 'store']);
        Route::delete('devices',                            [\App\Http\Controllers\Api\Mobile\DevicesController::class, 'destroy']);

        // Payment gateways — read-only listing of active gateways with
        // PUBLIC keys only (whitelisted per slug). Secrets stay on server.
        Route::get(   'payments/gateways',                  [\App\Http\Controllers\Api\Mobile\PaymentsController::class, 'gateways']);
        Route::post(  'payments/initiate',                  [\App\Http\Controllers\Api\Mobile\PaymentsController::class, 'initiate'])->middleware('throttle:sensitive');
        Route::post(  'payments/verify',                    [\App\Http\Controllers\Api\Mobile\PaymentsController::class, 'verify'])->middleware('throttle:sensitive');

        // Coupon listing + preview. `/coupons` returns publicly-valid
        // promos so the app can show "available offers"; `/coupons/validate`
        // computes the discount for a specific code + plan. Actual
        // redemption happens at /payments/initiate (which bumps times_used
        // only on a successful charge).
        Route::get(   'coupons',                            [\App\Http\Controllers\Api\Mobile\CouponsController::class, 'index']);
        Route::post(  'coupons/validate',                   [\App\Http\Controllers\Api\Mobile\CouponsController::class, 'validateCode'])->middleware('throttle:sensitive');

        // Channel integrations — connect / update / disconnect WhatsApp,
        // Twilio SMS, Telegram and Slack from inside the app. Credentials
        // are encrypted by ChannelIntegration::setCredentialsAttribute().
        Route::get(   'channels',                                       [\App\Http\Controllers\Api\Mobile\ChannelsController::class, 'index']);
        // Slack channel-list discovery + picker — must be declared BEFORE the
        // generic `channels/{channel}` routes below, otherwise Laravel's
        // pattern matcher would capture "slack" as the {channel} value and
        // route the request into store/update/destroy instead.
        Route::get(   'channels/slack/conversations',                   [\App\Http\Controllers\Api\Mobile\ChannelsController::class, 'slackConversations']);
        Route::put(   'channels/slack/selected-channel',                [\App\Http\Controllers\Api\Mobile\ChannelsController::class, 'slackSelectChannel']);
        Route::post(  'channels/{channel}',                             [\App\Http\Controllers\Api\Mobile\ChannelsController::class, 'store'])->middleware('throttle:sensitive');
        Route::put(   'channels/{channel}',                             [\App\Http\Controllers\Api\Mobile\ChannelsController::class, 'update'])->middleware('throttle:sensitive');
        Route::delete('channels/{channel}',                             [\App\Http\Controllers\Api\Mobile\ChannelsController::class, 'destroy']);

        // Help Center — topic cards + support tickets
        Route::get(   'help/topics',                        [\App\Http\Controllers\Api\Mobile\HelpController::class, 'topics']);
        Route::get(   'help/topics/{category}/articles',    [\App\Http\Controllers\Api\Mobile\HelpController::class, 'articles']);
        Route::get(   'help/articles/{slug}',               [\App\Http\Controllers\Api\Mobile\HelpController::class, 'article']);
        Route::post(  'help/articles/{slug}/feedback',      [\App\Http\Controllers\Api\Mobile\HelpController::class, 'feedback']);
        Route::get(   'help/tickets',                       [\App\Http\Controllers\Api\Mobile\HelpController::class, 'tickets']);
        Route::post(  'help/tickets',                       [\App\Http\Controllers\Api\Mobile\HelpController::class, 'submitTicket'])->middleware('throttle:sensitive');
        Route::get(   'help/tickets/{id}',                  [\App\Http\Controllers\Api\Mobile\HelpController::class, 'ticket'])->whereNumber('id');
        Route::post(  'help/tickets/{id}/replies',          [\App\Http\Controllers\Api\Mobile\HelpController::class, 'reply'])->whereNumber('id')->middleware('throttle:sensitive');
    });

    Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {

        // Contacts — require contacts scope
        Route::middleware('ability:contacts')->group(function () {
            Route::apiResource('contacts', Api\ContactController::class);
            Route::post('contacts/import', [Api\ContactController::class, 'import'])->middleware('throttle:sensitive');
            Route::get('contacts/export', [Api\ContactController::class, 'export'])->middleware('throttle:sensitive');
        });

        // Conversations — require conversations scope
        Route::middleware('ability:conversations')->group(function () {
            Route::apiResource('conversations', Api\ConversationController::class);
            Route::post('conversations/{conversation}/reply', [Api\ConversationController::class, 'reply']);
            Route::post('conversations/{conversation}/assign', [Api\ConversationController::class, 'assign']);
            Route::post('conversations/{conversation}/close', [Api\ConversationController::class, 'close']);
        });

        // Tags — require tags scope
        Route::middleware('ability:tags')->group(function () {
            Route::apiResource('tags', Api\TagController::class);
        });

        // Campaigns — require campaigns scope
        Route::middleware('ability:campaigns')->group(function () {
            Route::apiResource('campaigns', Api\CampaignController::class);
            Route::post('campaigns/{campaign}/send', [Api\CampaignController::class, 'send'])->middleware('throttle:sensitive');
        });

        // Workflows — require workflows scope
        Route::middleware('ability:workflows')->group(function () {
            Route::apiResource('workflows', Api\WorkflowController::class);
            Route::post('workflows/{workflow}/activate', [Api\WorkflowController::class, 'activate']);
            Route::post('workflows/{workflow}/pause', [Api\WorkflowController::class, 'pause']);
        });

        // Knowledge Base — require knowledge-base scope
        Route::middleware('ability:knowledge-base')->group(function () {
            Route::apiResource('knowledge-base', Api\KnowledgeBaseController::class);
            Route::post('knowledge-base/scrape', [Api\KnowledgeBaseController::class, 'scrape'])->middleware('throttle:sensitive');
        });

        // Temp Mail
        Route::middleware('ability:temp-mail')->prefix('temp-mail')->group(function () {
            Route::get('domains', [Api\TempMailController::class, 'domains']);
            Route::get('addresses', [Api\TempMailController::class, 'index']);
            Route::post('addresses', [Api\TempMailController::class, 'store']);
            Route::get('addresses/{uuid}', [Api\TempMailController::class, 'show']);
            Route::delete('addresses/{uuid}', [Api\TempMailController::class, 'destroy']);
            Route::get('addresses/{uuid}/messages', [Api\TempMailController::class, 'messages']);
            Route::get('messages/{uuid}', [Api\TempMailController::class, 'readMessage']);
        });

        // AI — require ai scope, stricter rate limits (expensive operations)
        Route::middleware('ability:ai')->group(function () {
            Route::post('ai/generate-reply', [Api\AIController::class, 'generateReply'])->middleware('throttle:sensitive');
            Route::post('ai/analyze-sentiment', [Api\AIController::class, 'analyzeSentiment'])->middleware('throttle:sensitive');
        });

        // Analytics — require analytics scope
        Route::middleware('ability:analytics')->group(function () {
            Route::get('analytics/overview', [Api\AnalyticsController::class, 'overview']);
            Route::get('analytics/ai', [Api\AnalyticsController::class, 'ai']);
            Route::get('analytics/team', [Api\AnalyticsController::class, 'team']);
        });

        // Canned Responses — require canned-responses scope
        Route::middleware('ability:canned-responses')->group(function () {
            Route::apiResource('canned-responses', Api\CannedResponseController::class);
        });

        // User & Workspace — no scope required (read-only, widely accessible)
        Route::get('user', fn (Request $request) => $request->user());
        Route::get('workspace', [Api\WorkspaceController::class, 'show']);
    });

}); // end v1
