<?php

use App\Http\Middleware\AdminMiddleware;
use App\Http\Middleware\CorsMiddleware;
use App\Http\Middleware\TenantMiddleware;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
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',
        health:   '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {

        // ── CORS for all API responses ────────────────────────────────────
        $middleware->append(CorsMiddleware::class);

        // ── Named route middleware aliases ────────────────────────────────
        $middleware->alias([
            'tenant' => TenantMiddleware::class,
            'admin'  => AdminMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {

        // ── Pretty JSON errors for API routes ────────────────────────────
        $exceptions->shouldRenderJsonWhen(
            fn(Request $request, \Throwable $e) => $request->expectsJson()
                || str_starts_with($request->path(), 'api/')
        );

        $exceptions->render(function (NotFoundHttpException $e, Request $request) {
            if (str_starts_with($request->path(), 'api/')) {
                return response()->json([
                    'error'   => 'Route পাওয়া যায়নি।',
                    'path'    => '/' . $request->path(),
                ], 404);
            }
        });

    })->create();
