<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Auth\AuthenticationException;
use Sentry\Laravel\Integration;
use App\Http\Middleware\HandleInertiaRequests;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__ . '/../routes/web.php',
        api: __DIR__ . '/../routes/api.php',
        commands: __DIR__ . '/../routes/console.php',
        channels: __DIR__ . '/../routes/channels.php',
        health: '/up',
        then: function () {
          
        },
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->web(append: [
            HandleInertiaRequests::class,
        ]);

        $middleware->validateCsrfTokens(except: [
            "/webhook/*" 
        ]);

        $middleware->alias([
            'admin' => \App\Http\Middleware\Admin::class,
            'staff' => \App\Http\Middleware\Staff::class,
            'apiuser' => \App\Http\Middleware\ApiUser::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {

        // handle api unauthorized
        $exceptions->render(function (AuthenticationException $e, $request) {
            if ($request->is('api/*')) {
                return response()->json([
                    'status' => false,
                    'data' => 'unauthenticated'
                ], 401);
            }
        });

        // handle api url not found
        $exceptions->render(function (NotFoundHttpException $e, $request) {
            if ($request->is('api/*')) {
                return response()->json([
                    'status' => false,
                    'data' => 'URL not found.'
                ], 404);
            }
        });

        Integration::handles($exceptions);
    })->create();
