<?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\Contact\InboxIndex;
use App\Http\Controllers\EsignWebhookController;
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', \App\Components\Platform\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('/inbox', InboxIndex::class)->lazy()->middleware('can:inbox.view')->name('inbox.index');
    Route::get('/inbox/triage', \App\Components\Contact\InboxTriage::class)->lazy()->middleware('can:inbox.view')->name('inbox.triage');
    Route::get('/inbox/attachments/{attachment}/download', \App\Http\Controllers\Contact\AttachmentDownloadController::class)
        ->middleware('can:inbox.view')
        ->name('inbox.attachment.download');
    Route::get('/inbox/attachments/{attachment}/preview', [\App\Http\Controllers\Contact\AttachmentDownloadController::class, 'preview'])
        ->middleware('can:inbox.view')
        ->name('inbox.attachment.preview');

    Route::get('/documents/{document}/view', \App\Components\Document\DocumentPreview::class)
        ->name('documents.view');
    Route::get('/documents/{document}/raw', [\App\Http\Controllers\Document\DocumentViewController::class, 'raw'])
        ->name('documents.raw');
    Route::get('/documents/{document}/zip-entry', [\App\Http\Controllers\Document\DocumentViewController::class, 'zipEntry'])
        ->name('documents.zipEntry');
    Route::post('/documents/{document}/review-wip', [\App\Http\Controllers\Document\DocumentViewController::class, 'bookReviewWip'])
        ->name('documents.reviewWip');
    Route::get('/documents/{document}/download', [\App\Http\Controllers\Document\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', \App\Components\Client\WipReview::class)->lazy()->middleware('can:view,client')->name('clients.wip');

    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', [\App\Http\Controllers\Institution\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', \App\Components\Dsar\Outstanding::class)->lazy()->middleware('can:dsars.view')->name('dsars.outstanding');
    Route::get('/dsars/report', \App\Components\Report\DsarReport::class)->lazy()->middleware('can:dsars.report')->name('dsars.report');
    Route::get('/dsars/report/institution/{institution}', \App\Components\Report\DsarInstitutionReport::class)->lazy()->middleware('can:dsars.report')->name('dsars.report.institution');
    Route::get('/dsars/report/client', \App\Components\Report\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}', \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', \App\Components\Report\StatusReport::class)->middleware('can:reports.status')->name('reports.status');
    Route::get('/reports/status/days', \App\Components\Report\DaysInStatusReport::class)->middleware('can:reports.status.days')->name('reports.status.days');
    Route::get('/reports/latest-actions', \App\Components\Report\LatestActionsReport::class)->lazy()->middleware('can:reports.latest-actions.view')->name('reports.latest-actions');
    Route::get('/reports/system-changes', \App\Components\Report\SystemChangesReport::class)->lazy()->middleware('can:reports.system-changes.view')->name('reports.system-changes');
    Route::get('/reports/trends', \App\Components\Report\TrendReport::class)->lazy()->middleware('can:reports.trends')->name('reports.trends');
    Route::get('/reports/pipeline-kpis', \App\Components\Report\PipelineKpis::class)->lazy()->middleware('can:reports.trends')->name('reports.pipeline-kpis');
    Route::get('/reports/kpis', \App\Components\Report\KpiReport::class)->lazy()->middleware('can:reports.trends')->name('reports.kpis');
    Route::get('/reports/agent-availability', \App\Components\Report\AgentAvailabilityReport::class)->lazy()->middleware('can:reports.agent-availability.view')->name('reports.agent-availability');
    Route::get('/reports/estimated-value-by-tranche', \App\Components\Report\EstimatedValueByTranche::class)->middleware('can:reports.estimated-value.tranches')->name('reports.estimated-value-by-tranche');

    Route::get('/reports/wip/tracking', \App\Components\Report\Wip\Tracking::class)->lazy()->middleware('can:reports.wip.tracking')->name('reports.wip.tracking');
    Route::get('/reports/wip/campaign-tranche', \App\Components\Report\Wip\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', \App\Components\DocumentTypeManager::class)->lazy()->middleware('can:doc-types.view')->name('doc-types.index');
    Route::get('/tags', \App\Components\Tag\TagManager::class)->lazy()->middleware('can:tags.view')->name('tags.index');
    Route::get('/key-dates', \App\Components\KeyDateManager::class)->lazy()->middleware('can:key-dates.view')->name('key-dates.index');
    Route::get('/institution-types', \App\Components\InstitutionTypeManager::class)->lazy()->middleware('can:institution-types.view')->name('institution-types.index');
    Route::get('/institution-record-types', \App\Components\InstitutionRecordTypeManager::class)->lazy()->middleware('can:institution-record-types.view')->name('institution-record-types.index');

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

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

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

    Route::get('/claims/{claim}/synapse/dsar-report', [\App\Http\Controllers\Synapse\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', \App\Components\Template\Editor::class)->middleware('can:templates.create')->name('templates.create');
        Route::get('/{template}', \App\Components\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', \App\Components\Contact\Admin\CommunicationLogIndex::class)
        ->name('communications.log');

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

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

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

    Route::get('/esign/settings', \App\Components\Esign\Admin\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', \App\Http\Controllers\Twilio\TwilioTokenController::class)->name('twilio.sdk.token');

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

Route::prefix('webhook/twilio')
    ->middleware('webhook.twilio')
    ->name('twilio.voice.')
    ->group(function ()
    {
        Route::post('/call', \App\Http\Controllers\Twilio\TwilioController::class)->name('call');
        Route::post('/status', \App\Http\Controllers\Twilio\TwilioStatusController::class)->name('status');
        Route::post('/recording', \App\Http\Controllers\Twilio\TwilioRecordingController::class)->name('recording');
        Route::post('/dial-fallback', \App\Http\Controllers\Twilio\TwilioDialFallbackController::class)->name('dial.fallback');
        Route::post('/transfer', \App\Http\Controllers\Twilio\TwilioTransferTwimlController::class)->name('transfer');
        Route::post('/transfer/fallback', \App\Http\Controllers\Twilio\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');