<?php

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

$app = 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 {
        $middleware->statefulApi();

        $middleware->web(append: [
            \App\Http\Middleware\HandleInertiaRequests::class,
            \Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
            \App\Http\Middleware\AffiliateReferralMiddleware::class,
            \App\Http\Middleware\CheckLicense::class,
        ]);

        $middleware->alias([
            'admin' => \App\Http\Middleware\AdminMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(function (\Illuminate\Database\QueryException $e, $request) {
            try {
                \Illuminate\Support\Facades\DB::connection()->getPdo();
                return null;
            } catch (\Exception $connException) {
                if ($request->expectsJson()) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Database tidak terhubung. Silakan konfigurasi database di halaman setup.',
                        'redirect' => route('setup')
                    ], 500);
                }
                if (!$request->is('setup') && !$request->is('setup/*')) {
                    return redirect()->route('setup');
                }
            }
        });

        $exceptions->render(function (\PDOException $e, $request) {
            try {
                \Illuminate\Support\Facades\DB::connection()->getPdo();
                return null;
            } catch (\Exception $connException) {
                if ($request->expectsJson()) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Database tidak terhubung. Silakan konfigurasi database di halaman setup.',
                        'redirect' => route('setup')
                    ], 500);
                }
                if (!$request->is('setup') && !$request->is('setup/*')) {
                    return redirect()->route('setup');
                }
            }
        });
    })->create();

$app->usePublicPath(dirname(__DIR__, 2));

return $app;
