<?php

use App\Components\Account\AccountProfile;
use App\Components\Account\AccountSecurity;
use App\Components\Account\AccountSessions;
use App\Components\Admin\Permission\PermissionCreate;
use App\Components\Admin\Permission\PermissionEdit;
use App\Components\Admin\Permission\PermissionIndex;
use App\Components\Admin\Role\RoleCreate;
use App\Components\Admin\Role\RoleEdit;
use App\Components\Admin\Role\RoleIndex;
use App\Components\Admin\Role\RoleShow;
use App\Components\Admin\Users\UserCreate;
use App\Components\Admin\Users\UserEdit;
use App\Components\Admin\Users\UserIndex;
use App\Components\Claim\CreateClaim;
use App\Components\Claim\StatusController;
use App\Components\Client\Create;
use App\Components\Client\Edit;
use App\Components\Client\Index;
use App\Components\Client\View;
use App\Components\Client\WipReview;
use App\Components\Contact\Admin\CommunicationLogIndex;
use App\Components\Contact\Admin\CommunicationsSettings;
use App\Components\Contact\BulkEmail\History;
use App\Components\Contact\BulkEmail\Station;
use App\Components\Contact\InboxIndex;
use App\Components\Contact\InboxTriage;
use App\Components\Dashboard\ClaimsHandlerDashboard;
use App\Components\Dashboard\LeadPerformanceDashboard;
use App\Components\Dialler\Dashboard;
use App\Components\Document\DocumentPreview;
use App\Components\DocumentTypeManager;
use App\Components\Dsar\Outstanding;
use App\Components\Dsar\TypeManager;
use App\Components\Esign\Admin\EsignSettings;
use App\Components\InstitutionRecordTypeManager;
use App\Components\InstitutionTypeManager;
use App\Components\KeyDateManager;
use App\Components\Platform\WorkspaceSelector;
use App\Components\PrintQueueManager;
use App\Components\Report\AgentAvailabilityReport;
use App\Components\Report\CohortReport;
use App\Components\Report\DaysInStatusReport;
use App\Components\Report\DsarClientReport;
use App\Components\Report\DsarInstitutionReport;
use App\Components\Report\DsarReport;
use App\Components\Report\EstimatedValueByTranche;
use App\Components\Report\KpiReport;
use App\Components\Report\LatestActionsReport;
use App\Components\Report\PipelineKpis;
use App\Components\Report\StatusReport;
use App\Components\Report\SystemChangesReport;
use App\Components\Report\TrendReport;
use App\Components\Report\Wip\CampaignTrancheReport;
use App\Components\Report\Wip\Tracking;
use App\Components\Tag\TagManager;
use App\Components\Task\TaskHub;
use App\Components\Template\Editor;
use App\Components\Workboard\WorkboardCategory;
use App\Components\Workboard\WorkboardCategoryManager;
use App\Components\Workboard\WorkboardIndex;
use App\Http\Controllers\Communication\RecordingStreamController;
use App\Http\Controllers\Contact\AttachmentDownloadController;
use App\Http\Controllers\Document\DocumentViewController;
use App\Http\Controllers\EsignWebhookController;
use App\Http\Controllers\Institution\SynapseContactController;
use App\Http\Controllers\PrintQueueController;
use App\Http\Controllers\Synapse\DsarReportController;
use App\Http\Controllers\Twilio\TwilioController;
use App\Http\Controllers\Twilio\TwilioDialFallbackController;
use App\Http\Controllers\Twilio\TwilioRecordingController;
use App\Http\Controllers\Twilio\TwilioStatusController;
use App\Http\Controllers\Twilio\TwilioTokenController;
use App\Http\Controllers\Twilio\TwilioTransferFallbackController;
use App\Http\Controllers\Twilio\TwilioTransferTwimlController;
use App\Http\Controllers\Webhooks\Communications\InboundEmailController;
use App\Http\Controllers\Webhooks\Communications\SendGridEventController;
use App\Http\Controllers\Webhooks\Communications\TwilioSmsStatusController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return redirect('login');
});

// Workspace selection — requires auth, no solicitor context needed
Route::middleware(['auth'])->group(function () {
    Route::get('/workspace', WorkspaceSelector::class)->name('workspace.select');
    Route::get('/workspace/switch', function () {
        session()->forget('workspace_solicitor_id');

        return redirect()->route('workspace.select');
    })->name('workspace.switch');
});

Route::prefix('account')
    ->name('account.')
    ->middleware(['auth', 'setSolicitor', 'ensureSolicitor', 'passSolicitorToView'])
    ->group(function () {
        Route::get('/profile', AccountProfile::class)->lazy()->name('profile');
        Route::get('/security', AccountSecurity::class)->lazy()->name('security');
        Route::get('/sessions', AccountSessions::class)->lazy()->name('sessions');
    });

Route::middleware(['auth', 'setSolicitor', 'ensureSolicitor', 'passSolicitorToView'])->group(function () {
    Route::get('/a', function () {
        return view('index');
    })->middleware('can:dashboard.view')->name('dashboard');

    Route::get('/claims-handler-dashboard', ClaimsHandlerDashboard::class)
        ->middleware('can:dashboard.view')
        ->name('claims-handler.dashboard');
    Route::get('/claims-handler-dashboard/{user}', ClaimsHandlerDashboard::class)
        ->middleware('can:users.view')
        ->name('claims-handler.dashboard.user');
    Route::get('/lead-performance', LeadPerformanceDashboard::class)
        ->middleware('can:lead-performance.view')
        ->name('lead-performance.dashboard');

    Route::get('/inbox', InboxIndex::class)->lazy()->middleware('can:inbox.view')->name('inbox.index');
    Route::get('/inbox/triage', InboxTriage::class)->lazy()->middleware('can:inbox.view')->name('inbox.triage');
    Route::get('/inbox/attachments/{attachment}/download', AttachmentDownloadController::class)
        ->middleware('can:inbox.view')
        ->name('inbox.attachment.download');
    Route::get('/inbox/attachments/{attachment}/preview', [AttachmentDownloadController::class, 'preview'])
        ->middleware('can:inbox.view')
        ->name('inbox.attachment.preview');

    Route::get('/documents/{document}/view', DocumentPreview::class)
        ->name('documents.view');
    Route::get('/documents/{document}/raw', [DocumentViewController::class, 'raw'])
        ->name('documents.raw');
    Route::get('/documents/{document}/zip-entry', [DocumentViewController::class, 'zipEntry'])
        ->name('documents.zipEntry');
    Route::post('/documents/{document}/review-wip', [DocumentViewController::class, 'bookReviewWip'])
        ->name('documents.reviewWip');
    Route::get('/documents/{document}/download', [DocumentViewController::class, 'download'])
        ->name('documents.download');

    Route::get('/clients', Index::class)->lazy()->middleware('can:clients.view')->name('clients.index');
    Route::get('/clients/create', Create::class)->lazy()->middleware('can:clients.create')->name('clients.create');
    Route::get('/clients/{client}/edit', Edit::class)->lazy()->middleware('can:edit,client')->name('clients.edit');
    Route::get('/clients/{client}', View::class)->lazy()->middleware('can:view,client')->name('clients.show');

    Route::get('/clients/{client}/create', CreateClaim::class)->middleware('can:claims.create')->name('claims.create');
    Route::get('/clients/{client}/claim', App\Components\Claim\Edit::class)->middleware('can:claims.edit')->name('claims.edit');

    Route::get('/clients/{client}/wip', WipReview::class)->lazy()->middleware('can:view,client')->name('clients.wip');

    Route::get('/clients/{client}/evidence', \App\Components\Client\EvidenceWorkbench::class)->middleware('can:view,client')->name('clients.evidence');
    Route::get('/clients/{client}/evidence/export', [\App\Http\Controllers\Client\EvidenceReviewExportController::class, 'download'])->middleware('can:view,client')->name('clients.evidence.export');

    // Witness Statement — full-page workspace (the production surface) + design exercise.
    Route::middleware('can:view,client')->prefix('clients/{client}/witness')->group(function () {
        Route::get('/', \App\Components\Client\Witness\WitnessWorkspace::class)->name('clients.witness.show');
        Route::get('/design', \App\Components\Client\Witness\WitnessDesignIndex::class)->name('clients.witness.design');
        Route::get('/design/compare', \App\Components\Client\Witness\WitnessDesignCompare::class)->name('clients.witness.design.compare');
        Route::get('/design/workspace', \App\Components\Client\Witness\WitnessWorkspace::class)->name('clients.witness.concept.workspace');
        Route::get('/design/builder', \App\Components\Client\Witness\WitnessBuilder::class)->name('clients.witness.concept.builder');
        Route::get('/design/split', \App\Components\Client\Witness\WitnessSplitView::class)->name('clients.witness.concept.split');
        Route::get('/design/dashboard', \App\Components\Client\Witness\WitnessReviewDashboard::class)->name('clients.witness.concept.dashboard');
    });

    Route::get('/sources', \App\Components\LeadSource\Index::class)->lazy()->middleware('can:sources.view')->name('sources.index');
    Route::get('/sources/create', \App\Components\LeadSource\Create::class)->lazy()->middleware('can:sources.create')->name('sources.create');
    Route::get('/sources/{leadSource}/edit', \App\Components\LeadSource\Edit::class)->lazy()->middleware('can:update,leadSource')->name('sources.edit');
    Route::get('/sources/{leadSource}', \App\Components\LeadSource\View::class)->lazy()->middleware('can:view,leadSource')->name('sources.show');

    Route::get('/institutions', App\Components\Institution\Index::class)->lazy()->middleware('can:institutions.view')->name('institutions.index');
    Route::get('/institutions/create', App\Components\Institution\Create::class)->lazy()->middleware('can:institutions.create')->name('institutions.create');
    Route::get('/institutions/{institution}/edit', App\Components\Institution\Edit::class)->lazy()->middleware('can:edit,institution')->name('institutions.edit');
    Route::post('/institutions/{institution}/synapse-contact', [SynapseContactController::class, 'store'])->middleware('can:institutions.contacts.create')->name('institutions.synapse-contact.store');
    Route::get('/institutions/{institution}', App\Components\Institution\View::class)->lazy()->middleware('can:view,institution')->name('institutions.show');

    Route::get('/dsars', Outstanding::class)->lazy()->middleware('can:dsars.view')->name('dsars.outstanding');
    Route::get('/dsars/report', DsarReport::class)->lazy()->middleware('can:dsars.report')->name('dsars.report');
    Route::get('/dsars/report/institution/{institution}', DsarInstitutionReport::class)->lazy()->middleware('can:dsars.report')->name('dsars.report.institution');
    Route::get('/dsars/report/client', DsarClientReport::class)->lazy()->middleware('can:dsars.report')->name('dsars.report.client');
    Route::get('/dsars/tranches/{tranche}', App\Components\Dsar\Tranche\View::class)->middleware('can:dsars.tranche.view')->name('dsars.tranches.view');
    Route::get('/dsars/types', \App\Components\Dsar\TypeManager::class)->lazy()->middleware('can:dsars.types.view')->name('dsars.types');
    Route::get('/dsars/{dsar}/evidence/{attachment}', \App\Components\Dsar\EvidenceViewerPage::class)->middleware('can:dsars.view')->name('dsars.evidence');
    Route::get('/documents/{document}/evidence', \App\Components\Dsar\DocumentEvidenceViewerPage::class)->middleware('can:dsars.view')->name('documents.evidence');
    Route::get('/dsars/{dsar}', \App\Components\Dsar\View::class)->middleware('can:dsars.view')->name('dsars.view');

    Route::get('/reports/tranche', App\Components\Report\Tranche\Index::class)->middleware('can:reports.tranches.view')->name('reports.tranche.index');
    Route::get('/reports/tranche/{tranche}', App\Components\Report\Tranche\View::class)->middleware('can:reports.tranches.view')->name('reports.tranche.view');
    Route::get('/reports/status', StatusReport::class)->middleware('can:reports.status')->name('reports.status');
    Route::get('/reports/status/days', DaysInStatusReport::class)->middleware('can:reports.status.days')->name('reports.status.days');
    Route::get('/reports/latest-actions', LatestActionsReport::class)->lazy()->middleware('can:reports.latest-actions.view')->name('reports.latest-actions');
    Route::get('/reports/system-changes', SystemChangesReport::class)->lazy()->middleware('can:reports.system-changes.view')->name('reports.system-changes');
    Route::get('/reports/trends', TrendReport::class)->lazy()->middleware('can:reports.trends')->name('reports.trends');
    Route::get('/reports/pipeline-kpis', PipelineKpis::class)->lazy()->middleware('can:reports.trends')->name('reports.pipeline-kpis');
    Route::get('/reports/kpis', KpiReport::class)->lazy()->middleware('can:reports.trends')->name('reports.kpis');
    Route::get('/reports/cohort', CohortReport::class)->lazy()->middleware('can:reports.trends')->name('reports.cohort');
    Route::get('/reports/agent-availability', AgentAvailabilityReport::class)->lazy()->middleware('can:reports.agent-availability.view')->name('reports.agent-availability');
    Route::get('/reports/estimated-value-by-tranche', EstimatedValueByTranche::class)->middleware('can:reports.estimated-value.tranches')->name('reports.estimated-value-by-tranche');

    Route::get('/reports/wip/tracking', Tracking::class)->lazy()->middleware('can:reports.wip.tracking')->name('reports.wip.tracking');
    Route::get('/reports/wip/campaign-tranche', CampaignTrancheReport::class)->middleware('can:reports.wip.view')->name('reports.wip.campaign-tranche');

    Route::get('/tranches', App\Components\Tranche\Index::class)->middleware('can:tranches.view')->name('tranches.index');

    Route::get('/statuses', StatusController::class)->lazy()->middleware('can:statuses.view')->name('statuses.index');
    Route::get('/doc-types', DocumentTypeManager::class)->lazy()->middleware('can:doc-types.view')->name('doc-types.index');
    Route::get('/tags', TagManager::class)->lazy()->middleware('can:tags.view')->name('tags.index');
    Route::get('/key-dates', KeyDateManager::class)->lazy()->middleware('can:key-dates.view')->name('key-dates.index');
    Route::get('/institution-types', InstitutionTypeManager::class)->lazy()->middleware('can:institution-types.view')->name('institution-types.index');
    Route::get('/institution-record-types', InstitutionRecordTypeManager::class)->lazy()->middleware('can:institution-record-types.view')->name('institution-record-types.index');

    Route::get('/task-hub', TaskHub::class)->middleware('can:tasks.admin')->name('task-hub.index');

    // Workboard — static /categories route must come before the {category} wildcard
    Route::get('/workboard', WorkboardIndex::class)->middleware('can:workboard.view')->name('workboard.index');
    Route::get('/workboard/categories', WorkboardCategoryManager::class)->middleware('can:workboard.manage')->name('workboard.categories.index');
    Route::get('/workboard/{category}', WorkboardCategory::class)->middleware('can:workboard.view')->name('workboard.category');

    Route::get('/print-queue', PrintQueueManager::class)->lazy()->middleware('can:print-queue.view')->name('print-queue.index');
    Route::get('/print-queue/{id}/preview', [PrintQueueController::class, 'preview'])->middleware('can:print-queue.view')->name('print-queue.preview');

    Route::get('/claims/{claim}/synapse/dsar-report', [DsarReportController::class, 'show'])->middleware('can:synapse.use')->name('claims.dsar-report');
    Route::prefix('templates')->group(function () {
        Route::get('/', App\Components\Template\Index::class)->middleware('can:templates.view')->name('templates.index');
        Route::get('/create', Editor::class)->middleware('can:templates.create')->name('templates.create');
        Route::get('/{template}', Editor::class)->middleware('can:templates.edit')->name('templates.edit');
    });

    Route::prefix('solicitors')->group(function () {
        Route::get('/', App\Components\Solicitor\Index::class)->name('solicitors.index');
        Route::get('/create', App\Components\Solicitor\Create::class)->name('solicitors.create');
        Route::get('/{solicitor}', App\Components\Solicitor\View::class)->name('solicitors.show');
        Route::get('/{solicitor}/edit', App\Components\Solicitor\Edit::class)->name('solicitors.edit');
    });

    Route::get('/communications/log', CommunicationLogIndex::class)
        ->name('communications.log');

    Route::prefix('communications/bulk-email')->middleware('can:communications.send.bulk')->group(function () {
        Route::get('/', Station::class)->name('communications.bulk-email');
        Route::get('/history', History::class)->name('communications.bulk-email.history');
    });

    Route::get('/dialler', Dashboard::class)->lazy()->name('dialler.dashboard');

    Route::get('/communications/settings', CommunicationsSettings::class)
        ->middleware('can:communications.settings.manage')
        ->name('communications.settings');

    Route::get('/esign/settings', EsignSettings::class)
        ->middleware('can:esign.settings.manage')
        ->name('esign.settings');

    Route::prefix('solicitors')->group(function () {
        Route::get('/', App\Components\Solicitor\Index::class)->middleware('can:solicitors.view')->name('solicitors.index');
        Route::get('/create', App\Components\Solicitor\Create::class)->middleware('can:solicitors.create')->name('solicitors.create');
        Route::get('/{solicitor}', App\Components\Solicitor\View::class)->middleware('can:solicitors.view')->name('solicitors.show');
        Route::get('/{solicitor}/edit', App\Components\Solicitor\Edit::class)->middleware('can:edit,solicitor')->name('solicitors.edit');
    });

    Route::get('/q')->name('settings.tools.index');
    Route::get('/w')->name('reports.status.claims');

    Route::get('/twilio/sdk/token', TwilioTokenController::class)->name('twilio.sdk.token');

    // Recording audio stream (serves local storage files or proxies to external URL)
    Route::get('/recordings/{recording}/stream', RecordingStreamController::class)->name('recordings.stream');
});

Route::prefix('webhook/twilio')
    ->middleware('webhook.twilio')
    ->name('twilio.voice.')
    ->group(function () {
        Route::post('/call', TwilioController::class)->name('call');
        Route::post('/status', TwilioStatusController::class)->name('status');
        Route::post('/recording', TwilioRecordingController::class)->name('recording');
        Route::post('/dial-fallback', TwilioDialFallbackController::class)->name('dial.fallback');
        Route::post('/transfer', TwilioTransferTwimlController::class)->name('transfer');
        Route::post('/transfer/fallback', TwilioTransferFallbackController::class)->name('transfer.fallback');
    });

Route::middleware(['web', 'auth', 'platform'])->group(function () {
    Route::get('/monitoring', App\Components\Monitoring\Index::class)->middleware('can:monitoring.view')->name('monitoring.index');
});

Route::middleware(['web', 'auth', 'setSolicitor', 'platform', 'passSolicitorToView'])
    ->prefix('admin')
    ->name('admin.')
    ->group(function () {

        /*
        |--------------------------------------------------------------------------
        | USERS
        |--------------------------------------------------------------------------
        */
        Route::prefix('users')->name('users.')->group(function () {

            Route::get('/', UserIndex::class)->lazy()->middleware('can:users.view')->name('index');
            Route::get('/create', UserCreate::class)->lazy()->middleware('can:users.create')->name('create');
            Route::get('/{user}', App\Components\Admin\Users\View::class)->middleware('can:users.view')->name('show');
            Route::get('/{user}/edit', UserEdit::class)->lazy()->middleware('can:edit,user')->name('edit');
        });

        Route::post('/users/stop-impersonation', function () {
            if (! session()->has('impersonator_id')) {
                return redirect('/');
            }

            Auth::loginUsingId(session()->pull('impersonator_id'));

            return redirect()->route('admin.users.index');
        })->name('users.stop-impersonation');

        /*
        |--------------------------------------------------------------------------
        | ROLES
        |--------------------------------------------------------------------------
        */
        Route::prefix('roles')->name('roles.')->group(function () {
            Route::get('/', RoleIndex::class)->lazy()->middleware('can:roles.view')->name('index');
            Route::get('/create', RoleCreate::class)->lazy()->middleware('can:roles.create')->name('create');
            Route::get('/{role}', RoleShow::class)->lazy()->middleware('can:view,role')->name('show');
            Route::get('/{role}/edit', RoleEdit::class)->lazy()->middleware('can:edit,role')->name('edit');
        });

        /*
        |--------------------------------------------------------------------------
        | PERMISSIONS
        |--------------------------------------------------------------------------
        */
        Route::prefix('permissions')->name('permissions.')->group(function () {
            Route::get('/', PermissionIndex::class)->lazy()->middleware('can:permissions.view')->name('index');
            Route::get('/create', PermissionCreate::class)->lazy()->middleware('can:permissions.create')->name('create');
            Route::get('/{permission}/edit', PermissionEdit::class)->lazy()->middleware('can:permissions.edit')->name('edit');
        });
    });

Route::post('/webhook/esign', [EsignWebhookController::class, 'input'])
    ->middleware('throttle:120,1')
    ->name('webhook.esign');

Route::prefix('webhooks/contact')->name('webhooks.contact.')->group(function () {
    Route::post('/sendgrid', SendGridEventController::class)
        ->middleware('webhook.sendgrid')
        ->name('sendgrid');

    Route::post('/sendgrid/inbound/{token}', InboundEmailController::class)
        ->withoutMiddleware(['web', 'auth'])
        ->middleware('throttle:60,1')
        ->name('sendgrid.inbound');

    Route::post('/twilio/sms/status', TwilioSmsStatusController::class)
        ->middleware('webhook.twilio')
        ->name('twilio.sms.status');
});

Route::view('/api-docs/lead-intake', 'api-docs.lead-intake')
    ->name('api-docs.lead-intake');
