<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Maestro\Core\Http\Controllers\ActivityLogController;
use Maestro\Core\Http\Controllers\Api\DataTables\DataTableController;
use Maestro\Core\Http\Controllers\Api\DataTables\DataTableExportController;
use Maestro\Core\Http\Controllers\Api\UserTableStateController;
use Maestro\Core\Http\Controllers\AppSettingsController;
use Maestro\Core\Http\Controllers\Auth\AuthenticatedSessionController;
use Maestro\Core\Http\Controllers\Auth\MicrosoftAuthController;
use Maestro\Core\Http\Controllers\CoreBrandingAssetController;
use Maestro\Core\Http\Controllers\NavigationController;
use Maestro\Core\Http\Controllers\OrganizationController;
use Maestro\Core\Http\Controllers\PermissionListController;
use Maestro\Core\Http\Controllers\RoleSettingsController;
use Maestro\Core\Http\Controllers\Superadmin\DataTableColumnDefaultsController;
use Maestro\Core\Http\Controllers\Superadmin\InstallationHealthController;
use Maestro\Core\Http\Controllers\Superadmin\MaestroAppSettingsController;
use Maestro\Core\Http\Controllers\Superadmin\MaestroModuleController;
use Maestro\Core\Http\Controllers\Superadmin\PublicPageHealthController;
use Maestro\Core\Http\Controllers\Superadmin\SuperadminNavigationController;
use Maestro\Core\Http\Controllers\Superadmin\SuperadminUsersController;
use Maestro\Core\Http\Controllers\Superadmin\UserTableStateResetController;
use Maestro\Core\Http\Controllers\UserManagementController;
use Maestro\Core\Http\Middleware\EnsurePlatformSuperadmin;
use Maestro\Core\Support\AuthenticatedUserApiPayload;

Route::middleware('web')->group(function () {
    Route::post('/login', [AuthenticatedSessionController::class, 'store'])
        ->middleware('guest')
        ->name('login.store');

    Route::get('/auth/microsoft/redirect', [MicrosoftAuthController::class, 'redirect'])
        ->middleware('guest')
        ->name('auth.microsoft.redirect');

    Route::get('/auth/microsoft/callback', [MicrosoftAuthController::class, 'callback'])
        ->middleware('guest')
        ->name('auth.microsoft.callback');

    Route::post('/logout', [AuthenticatedSessionController::class, 'destroy'])
        ->middleware('auth')
        ->name('logout');

    Route::get('/vendor/maestro/branding/{file}', [CoreBrandingAssetController::class, 'show'])
        ->where('file', '[a-zA-Z0-9._-]+\.(png|jpg|jpeg|webp|gif|ico|svg)')
        ->name('maestro.core.branding-asset');

    Route::get('/api/app-settings', [AppSettingsController::class, 'show'])
        ->name('api.app-settings');

    Route::middleware('auth')->prefix('api')->group(function () {
        Route::get('/user', function (Request $request) {
            return response()->json(
                AuthenticatedUserApiPayload::toArray($request->user())
            );
        })->name('api.user');

        Route::get('/organization', [OrganizationController::class, 'show']);
        Route::patch('/organization', [OrganizationController::class, 'update']);

        Route::get('/permissions', [PermissionListController::class, 'index']);

        Route::get('/navigation', [NavigationController::class, 'index']);

        $tableKeyPattern = '[\w\.\-]+';
        Route::get('/user/table-states/{tableKey}', [UserTableStateController::class, 'show'])
            ->where('tableKey', $tableKeyPattern);
        Route::put('/user/table-states/{tableKey}', [UserTableStateController::class, 'update'])
            ->where('tableKey', $tableKeyPattern);
        Route::delete('/user/table-states/{tableKey}', [UserTableStateController::class, 'destroy'])
            ->where('tableKey', $tableKeyPattern);

        Route::middleware([EnsurePlatformSuperadmin::class])->prefix('superadmin')->group(function () {
            Route::get('/installation-health', InstallationHealthController::class);
            Route::get('/modules', [MaestroModuleController::class, 'index']);
            Route::post('/modules/{slug}/activate', [MaestroModuleController::class, 'activate']);
            Route::patch('/modules/{slug}/installation', [MaestroModuleController::class, 'setInstallationState']);
            Route::patch('/modules/{slug}/runtime', [MaestroModuleController::class, 'setRuntimeState']);
            Route::get('/navigation-tree', [SuperadminNavigationController::class, 'show']);
            Route::put('/navigation-tree', [SuperadminNavigationController::class, 'update']);
            Route::patch('/app-settings', [MaestroAppSettingsController::class, 'update']);
            Route::get('/public-page-health', PublicPageHealthController::class);
            Route::post('/branding', [MaestroAppSettingsController::class, 'uploadBranding']);
            Route::post('/branding/offer-document-background', [MaestroAppSettingsController::class, 'uploadOfferDocumentBackground']);
            Route::delete('/branding/offer-document-background/{index}', [MaestroAppSettingsController::class, 'deleteOfferDocumentBackground'])
                ->whereNumber('index');
            Route::delete('/branding/{slot}', [MaestroAppSettingsController::class, 'clearBranding']);
            Route::get('/users-minimal', [SuperadminUsersController::class, 'index']);
            Route::get('/datatable-column-defaults', [DataTableColumnDefaultsController::class, 'index']);
            $resourceKeySa = '^(?!exports$)[a-z0-9_-]+$';
            Route::put('/datatable-column-defaults/{resourceKey}', [DataTableColumnDefaultsController::class, 'update'])
                ->where('resourceKey', $resourceKeySa);
            Route::delete('/datatable-column-defaults/{resourceKey}', [DataTableColumnDefaultsController::class, 'destroy'])
                ->where('resourceKey', $resourceKeySa);
            Route::post('/user-table-state/reset', UserTableStateResetController::class);
        });

        Route::get('/users', [UserManagementController::class, 'index']);
        Route::post('/users', [UserManagementController::class, 'store']);
        Route::patch('/users/{user}', [UserManagementController::class, 'update']);
        Route::delete('/users/{user}', [UserManagementController::class, 'destroy']);

        Route::get('/roles', [RoleSettingsController::class, 'index']);
        Route::post('/roles', [RoleSettingsController::class, 'store']);
        Route::put('/roles/{role}', [RoleSettingsController::class, 'update']);
        Route::delete('/roles/{role}', [RoleSettingsController::class, 'destroy']);

        Route::get('/settings/activity-log', [ActivityLogController::class, 'index']);

        Route::prefix('datatables')->group(function (): void {
            Route::get('exports', [DataTableExportController::class, 'index']);
            Route::post('exports/clear-ready', [DataTableExportController::class, 'clearReady']);
            Route::get('exports/{id}', [DataTableExportController::class, 'show'])->whereUuid('id');
            Route::get('exports/{id}/download', [DataTableExportController::class, 'download'])->whereUuid('id');

            // Avoid conflict with POST .../exports as a bogus resource fetch.
            $resourcePattern = '^(?!exports$)[a-z0-9_-]+$';
            Route::get('{resourceKey}/columns', [DataTableController::class, 'columns'])->where('resourceKey', $resourcePattern);
            Route::post('{resourceKey}/export', [DataTableController::class, 'export'])->where('resourceKey', $resourcePattern);
            Route::post('{resourceKey}', [DataTableController::class, 'fetch'])->where('resourceKey', $resourcePattern);
        });
    });
});

/*
|--------------------------------------------------------------------------
| SPA fallback
|--------------------------------------------------------------------------
|
| Host applications must register a single catch-all route (see stubs/routes/web.php)
| that returns the SPA Blade view. Duplicate global fallbacks cause confusing route
| precedence; this package does not register one.
|
*/
