<?php


use App\Http\Controllers\AssetController;
use App\Http\Controllers\ExportMapTemplateController;
use App\Http\Controllers\LeadExportTemplateController;
use App\Http\Controllers\NotificationTemplateController;
use App\Http\Controllers\MediaController;
use App\Http\Controllers\ModelRequestController;
use App\Http\Controllers\ReleaseNoteController;
use App\Http\Controllers\SpecDocumentAttachmentController;
use App\Http\Controllers\SpecDocumentController;
use App\Http\Controllers\SpecDocumentSectionController;
use App\Http\Controllers\SpecDocumentSectionTemplateController;
use App\Http\Controllers\TaxonomyController;
use App\Http\Controllers\TwoFactorDeviceController;
use App\Http\Controllers\UserController;
use App\Http\Middleware\ImpersonateSanctum;
use App\Http\Middleware\InitializeTenancyBySiteInRequest;
use App\Master\Http\Controllers\AllUserController;
use App\Master\Http\Controllers\ApiAuthController;
use App\Master\Http\Controllers\ApiUsageController;
use App\Master\Http\Controllers\ApiUserController;
use App\Master\Http\Controllers\BillableController;
use App\Master\Http\Controllers\CommandController;
use App\Master\Http\Controllers\CronLogController;
use App\Master\Http\Controllers\ContentSyncController;
use App\Master\Http\Controllers\CapVehicleController;
use App\Master\Http\Controllers\EVDataController;
use App\Master\Http\Controllers\FeatureFlagController;
use App\Master\Http\Controllers\ImpersonateController;
use App\Master\Http\Controllers\ImpersonationRequestController;
use App\Master\Http\Controllers\InvoiceController;
use App\Master\Http\Controllers\RoleController;
use App\Master\Http\Controllers\SiteController;
use App\Master\Http\Controllers\SiteDomainController;
use App\Master\Http\Controllers\SystemDashboardController;
use App\Master\Http\Controllers\UploadProfilePhotoController;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Route;
use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData;

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

Route::middleware('auth:sanctum')->get('/user', [UserController::class, 'show']);

Route::post('/token', [ApiAuthController::class, 'token']);

Route::post('/content-sync/provide-entries', [ContentSyncController::class, 'provideEntries']);
Route::put('/content-sync/perform', [ContentSyncController::class, 'receiveDataFromRemote']);

Route::middleware(['throttle:site-domains'])->group(function () {
    Route::get('/site-domains/v2', [SiteDomainController::class, 'domainsWithPorts']);
    Route::get('/site-domains', [SiteDomainController::class, 'listDomains']);
});

Route::middleware('auth:sanctum')->group(function (Router $router) {
    $router->post('/user/profile-photo', [UploadProfilePhotoController::class, 'update']);
    $router->get('/user', [UserController::class, 'show'])->name('users.show');
    $router->post('/user/set-site', [UserController::class, 'setSite'])->name('users.set-site');
    $router->post('/user/toggle-favourite-site', [UserController::class, 'toggleFavouriteSite'])->name('users.toggle-favourite-site');

    // Two-factor remembered devices management
    $router->get('/user/two-factor-devices', [TwoFactorDeviceController::class, 'index'])->name('two-factor-devices.index');
    $router->delete('/user/two-factor-devices/{id}', [TwoFactorDeviceController::class, 'destroy'])->name('two-factor-devices.destroy');
    $router->delete('/user/two-factor-devices', [TwoFactorDeviceController::class, 'destroyAll'])->name('two-factor-devices.destroy-all');
    $router->get('sites/queues', [SiteController::class, 'queueLengths'])->name('sites.queue-lengths');
    $router->get('sites/failed-jobs', [SiteController::class, 'failedJobs'])->name('sites.failed-jobs');
    $router->get('get-roles', [SiteController::class, 'roles'])->name('sites.roles');
    $router->post('stop-impersonate', [ImpersonateController::class, 'stopImpersonate'])
        ->withoutMiddleware(ImpersonateSanctum::class)
        ->name('stop-impersonate');

    // Model Requests (user submission - available to all authenticated users)
    $router->post('model-requests', [ModelRequestController::class, 'store']);

    $router->middleware([
        'role:' . config('mtc_login.mtc_user_role')
    ])->group(function (Router $router) {
        $router->get('trigger-command', [CommandController::class, 'index']);
        $router->post('trigger-command', [CommandController::class, 'store']);

        $router->middleware([
            InitializeTenancyBySiteInRequest::class
        ])->group(function (Router $router) {
            $router->get('sites/{tenant}/go-live', [SiteController::class, 'goLiveTasks'])->name('sites.get-go-live-tasks');
            $router->post('sites/{tenant}/go-live/{key}', [SiteController::class, 'triggerGoLiveTask'])->name('sites.start-go-live-task');
            $router->post('sites/{tenant}/all-go-live', [SiteController::class, 'triggerAllGoLive'])->name('sites.start-go-live-task');
        });

        $router->middleware([
            InitializeTenancyBySiteInRequest::class
        ])->group(function (Router $router) {
            $router->post('sites/{tenant}/go-live/{key}', [SiteController::class, 'triggerGoLiveTask'])->name('sites.start-go-live-task');
            $router->post('sites/{tenant}/all-go-live', [SiteController::class, 'triggerAllGoLive'])->name('sites.all-go-live-tasks');
            $router->post('sites/{tenant}/reset-go-live', [SiteController::class, 'resetGoLive'])->name('sites.reset-go-live-tasks');
        });

        $router->post('impersonate-user/{user}', [ImpersonateController::class, 'impersonate'])->name('impersonate');

        // Impersonation Requests
        $router->get('impersonation-requests', [ImpersonationRequestController::class, 'index']);
        $router->post('impersonation-requests', [ImpersonationRequestController::class, 'store']);
        $router->post('impersonation-requests/{id}/approve', [ImpersonationRequestController::class, 'approve']);
        $router->post('impersonation-requests/{id}/reject', [ImpersonationRequestController::class, 'reject']);
        $router->put('sites/{site}/trigger-action', [SiteController::class, 'triggerAction'])->name('sites.trigger-action');
        $router->post('sites/{site}/clear-cloudflare', [SiteController::class, 'clearCloudflare'])->name('sites.clear-cloudflare');
        $router->get('sites/{site}/billing', [SiteController::class, 'billing'])->name('sites.get-billing');
        $router->put('sites/{site}/billing', [SiteController::class, 'updateBilling'])->name('sites.updateBilling');
        $router->post('sites/{site}/invite', [SiteController::class, 'invite'])->name('sites.invite-user');
        $router->post('sites/{site}/remove-user', [SiteController::class, 'removeUser'])->name('sites.remove-user');
        $router->post('sites/{site}/update-user', [SiteController::class, 'updateUserRole'])->name('sites.update-user');
        $router->post('sites/{site}/mark-live', [SiteController::class, 'markLive'])->name('sites.mark-live');
        $router->post('sites/{site}/suspend', [SiteController::class, 'suspendSite'])->name('sites.suspend');
        $router->post('sites/{site}/unsuspend', [SiteController::class, 'unsuspendSite'])->name('sites.unsuspend');
        $router->post('sites/integrations', [SiteController::class, 'integrations'])->name('sites.integrations');
        $router->resource('sites', SiteController::class)->only(['index', 'store', 'destroy']);

        $router->put('all-users/{user}/require-password-change', [AllUserController::class, 'requirePasswordChange'])
            ->name('user-management.require-password-change');
        $router->put('all-users/{user}/reset-password', [AllUserController::class, 'resetPassword'])
            ->name('user-management.reset-password');
        $router->put('all-users/{user}/reset-2fa', [AllUserController::class, 'reset2FactorAuth'])
            ->name('user-management.reset-two-factor');
        $router->put('all-users/{user}/toggle-permission', [AllUserController::class, 'togglePermission'])
            ->name('user-management.toggle-permission');
        $router->post('all-users', [AllUserController::class, 'store'])->name('all-users.store');
        $router->put('all-users/{user}/toggle-stakeholder', [AllUserController::class, 'toggleStakeholder'])
            ->name('user-management.toggle-stakeholder');
        $router->get('all-users-export/mailing-list', [AllUserController::class, 'exportStakeholderMailingList'])
            ->name('user-management.export-mailing-list');
        $router->resource('all-users', AllUserController::class)->only(['index', 'show', 'destroy']);
        $router->apiResource('roles', RoleController::class);

        $router->apiResource('release-notes', ReleaseNoteController::class);
        $router->apiResource('export-map-templates', ExportMapTemplateController::class);
        $router->apiResource('lead-export-templates', LeadExportTemplateController::class);
        $router->apiResource('notification-templates', NotificationTemplateController::class);

        $router->get('spec-documents/options', [SpecDocumentController::class, 'options'])
            ->name('spec-documents.options');
        $router->get('spec-document-templates', [SpecDocumentSectionTemplateController::class, 'index'])
            ->name('spec-document-templates.index');
        $router->put('spec-document-templates/{type}', [SpecDocumentSectionTemplateController::class, 'update'])
            ->name('spec-document-templates.update');
        $router->post('spec-documents/{spec_document}/sign-off', [SpecDocumentController::class, 'signOff'])
            ->name('spec-documents.sign-off');
        $router->get('spec-documents/{spec_document}/preview-link', [SpecDocumentController::class, 'previewLink'])
            ->name('spec-documents.preview-link');
        $router->get('spec-documents/{spec_document}/preview', [SpecDocumentController::class, 'preview'])
            ->middleware('signed')
            ->name('spec-documents.preview');
        $router->put('spec-documents/{spec_document}/sections-reorder', [SpecDocumentController::class, 'reorderSections'])
            ->name('spec-documents.sections.reorder');
        $router->post('spec-documents/{spec_document}/sections', [SpecDocumentSectionController::class, 'store'])
            ->name('spec-documents.sections.store');
        $router->put(
            'spec-documents/{spec_document}/sections/{section}',
            [SpecDocumentSectionController::class, 'update']
        )->name('spec-documents.sections.update');
        $router->delete(
            'spec-documents/{spec_document}/sections/{section}',
            [SpecDocumentSectionController::class, 'destroy']
        )->name('spec-documents.sections.destroy');
        $router->post('spec-documents/{spec_document}/attachments', [SpecDocumentAttachmentController::class, 'store'])
            ->name('spec-documents.attachments.store');
        $router->delete(
            'spec-documents/{spec_document}/attachments/{attachment}',
            [SpecDocumentAttachmentController::class, 'destroy']
        )->name('spec-documents.attachments.destroy');
        $router->apiResource('spec-documents', SpecDocumentController::class);
        $router->post('api-users/{apiUser}/create-credentials', [ApiUserController::class, 'createCredentials']);
        $router->delete('api-users/{apiUser}/expire-token/{token}', [ApiUserController::class, 'expireToken']);
        $router->get('api-users/{apiUser}/usage', [ApiUserController::class, 'usage']);
        $router->apiResource('api-users', ApiUserController::class);

        $router->get('api-usage', [ApiUsageController::class, 'index']);
        $router->get('api-usage/endpoints', [ApiUsageController::class, 'endpoints']);

        $router->get('cron-logs', [CronLogController::class, 'index']);

        $router->get('feature-flags', [FeatureFlagController::class, 'index']);
        $router->get('feature-flags/{feature}', [FeatureFlagController::class, 'show']);

        $router->get('system-dashboard', [SystemDashboardController::class, 'index'])->name('system-dashboard.index');
        $router->get('system-dashboard/tenants', [SystemDashboardController::class, 'tenants'])->name('system-dashboard.tenants');
        $router->get('api-usage/by-date/{date}', [ApiUsageController::class, 'byDate']);
        $router->get('api-usage/by-date/{date}/tenant/{tenant}', [ApiUsageController::class, 'byTenant']);
        $router->get('api-usage/snapshots/{date}/{tenant}/{method}', [ApiUsageController::class, 'snapshots']);
        $router->get('api-usage/snapshot/{id}', [ApiUsageController::class, 'snapshotInput']);

        $router->get('taxonomies', [TaxonomyController::class, 'index']);
        $router->get('taxonomies/providers', [TaxonomyController::class, 'providers']);
        $router->get('taxonomies/makes-list', [TaxonomyController::class, 'makesList']);
        $router->get('taxonomies/unmapped', [TaxonomyController::class, 'unmapped']);
        $router->post('taxonomies/from-unmapped', [TaxonomyController::class, 'storeUnmapped']);
        $router->get('taxonomies/mapped', [TaxonomyController::class, 'mapped']);
        $router->post('taxonomies/clear-mapped/{taxonomyMap}', [TaxonomyController::class, 'clearMapped']);
        $router->get('taxonomies/{type}/{id}', [TaxonomyController::class, 'showEntry']);
        $router->put('taxonomies/{type}/{id}', [TaxonomyController::class, 'updateEntry']);
        $router->delete('taxonomies/{type}/{id}', [TaxonomyController::class, 'destroy']);
        $router->get('taxonomies/{type}', [TaxonomyController::class, 'show']);
        $router->post('taxonomies/{type}', [TaxonomyController::class, 'store']);
        $router->put('taxonomies/{map}', [TaxonomyController::class, 'update']);

        // Model Requests (admin)
        $router->get('model-requests', [ModelRequestController::class, 'index']);
        $router->get('model-requests/makes', [ModelRequestController::class, 'makes']);
        $router->get('model-requests/{id}', [ModelRequestController::class, 'show'])->where('id', '[0-9]+');
        $router->post('model-requests/{id}/approve', [ModelRequestController::class, 'approve']);
        $router->post('model-requests/{id}/reject', [ModelRequestController::class, 'reject']);

        $router->resource('invoices', InvoiceController::class)->only(['index', 'show']);
        $router->resource('billables', BillableController::class)->only(['index']);

        $router->apiResource('ev-data', EVDataController::class)->only(['index', 'show']);

        $router->get('cap-vehicles/stats', [CapVehicleController::class, 'stats'])->name('cap-vehicles.stats');
        $router->post('cap-vehicles/upload', [CapVehicleController::class, 'upload'])->name('cap-vehicles.upload');
        $router->apiResource('cap-vehicles', CapVehicleController::class)->only(['index', 'show']);

        $router->post('/assets/global', [AssetController::class, 'globalStore']);

        $router->post('/content-sync/get-entries', [ContentSyncController::class, 'getRemoteEntries']);
        $router->put('/content-sync/{sync}', [ContentSyncController::class, 'update']);
        $router->post('/content-sync/{sync}/renew-token', [ContentSyncController::class, 'renewToken'])
            ->name('content-sync.renew-token');
        $router->post('/content-sync/{sync}/approve', [ContentSyncController::class, 'approve'])
            ->name('content-sync.approve');
        $router->post('/content-sync/{sync}/reject', [ContentSyncController::class, 'reject'])
            ->name('content-sync.reject');
        $router->put('/content-sync', [ContentSyncController::class, 'run']);
        $router->resource('/content-sync', ContentSyncController::class)->only(['index', 'store', 'show']);
    });

    $router->post('/content/media', [MediaController::class, 'store'])
        ->middleware([
            InitializeTenancyByRequestData::class,
            implode(',', config('pages.route_middleware.media')),
        ])
        ->name('content.media.store');
});
