<?php

declare(strict_types=1);

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Spatie\Csp\AddCspHeaders;
use Spatie\Honeypot\ProtectAgainstSpam;
use TechnoArtisan\FilamentCms\Http\Controllers\ContactController;
use TechnoArtisan\FilamentCms\Http\Controllers\PageController;
use TechnoArtisan\FilamentCms\Http\Middleware\Localization;
use TechnoArtisan\FilamentCms\Http\Middleware\SecurityHeaders;

// handle stage-specific middlewares
$middlewares = in_array(app()->environment(), config('filament-cms.ssl-environments'), true)
    ? [SecurityHeaders::class, AddCspHeaders::class, Localization::class, 'web']
    : [Localization::class, 'web'];

/**
 * mandatory middleware group 'web', otherwise no session, ... !!!
 */
Route::middleware($middlewares)->group(function () {
//Route::middleware([Localization::class, 'web'])->group(function () {
    // need to redirect from "/" (root) to detect or fallback locale
    Route::get('/', static function () {
        return redirect(app()->getLocale());
    });

    // route all language prefixed request to the WebController
    Route::prefix('{'.config('filament-cms.route_config.variable').'}')
         ->where([
                     config('filament-cms.route_config.variable')
                     => '('.implode('|', config('filament-cms.locale.available')).'){1}',
                 ])
         ->group(function () {
             Route::get('{page?}', [PageController::class, 'index'])
                  ->where('page', '[a-zA-Z0-9\-\/]*')
                  ->name('all')
             ;

             Route::post('{page?}', [ContactController::class, 'store'])
                  ->where('page', '[a-zA-Z0-9\-]*')
                  ->middleware([ProtectAgainstSpam::class, 'throttle:5,1'])
                  ->name('contact-post')
             ;
         })
    ;
});

Route::fallback(function (Request $request) {
    // access the current path
    $path = $request->path();

    // Check if it's an API request
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Not Found'], 404);
    }

    // set the necessary locale into app
    app()->setLocale($request->getPreferredLanguage(
        config(TechnoArtisan\FilamentCms\FilamentCms::getPackageName().'.locale.available')
    ));

    // load the package + theme specific 404 error view
    return response()->view(
        TechnoArtisan\FilamentCms\FilamentCms::getViewPrefix().'.errors.404',
        [
            'path'             => $path,
            'pageKey'          => 'home',
            'currentLocale'    => $request->getPreferredLanguage(
                config(TechnoArtisan\FilamentCms\FilamentCms::getPackageName().'.locale.available')
            ),
            'languageSwitcher' => getPreparedLanguageSelectorData('home'),
        ],
        404
    );
});
