<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // Coolify/Traefik SSL'i kendi katmanında sonlandırıyor; X-Forwarded-* header'larına
        // güvenmezsek route()/url() hep http:// üretir (mixed content hatalarına yol açar).
        $middleware->trustProxies(
            at: '*',
            headers: Request::HEADER_X_FORWARDED_FOR
                | Request::HEADER_X_FORWARDED_HOST
                | Request::HEADER_X_FORWARDED_PORT
                | Request::HEADER_X_FORWARDED_PROTO
                | Request::HEADER_X_FORWARDED_AWS_ELB,
        );
        $middleware->alias([
            'admin'         => \App\Http\Middleware\AdminMiddleware::class,
            'admin.access'  => \App\Http\Middleware\AdminAccessMiddleware::class,
            'import.api'    => \App\Http\Middleware\ImportApiMiddleware::class,
            'secure.player' => \App\Http\Middleware\SecurePlayer::class,
        ]);
        // Giriş yapılmamış kullanıcıyı frontend login sayfasına yönlendir
        $middleware->redirectGuestsTo(fn () => route('frontend.login'));
        // Bot koruması tüm web isteklerine uygula
        $middleware->web(\App\Http\Middleware\BotDetector::class);
        // SEO yönlendirmeleri
        $middleware->web(\App\Http\Middleware\SeoRedirectMiddleware::class);
        // iyzico callback ve arka plan izleme metrikleri (beacon/fetch) CSRF muaf
        $middleware->validateCsrfTokens(except: [
            'checkout/callback',
            'track/*',
            'api/*',
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();
