<?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',
        apiPrefix: 'api',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // 미들웨어 별칭 등록
        $middleware->alias([
            'hq.member' => \App\Http\Middleware\EnsureHQMember::class,
            'super.admin' => \App\Http\Middleware\EnsureSuperAdmin::class,
            'password.changed' => \App\Http\Middleware\EnsurePasswordChanged::class,
        ]);

        // CSRF 토큰 검증 예외 (외부 API 호출용)
        $middleware->validateCsrfTokens(except: [
            'menu-sync/*',
            'common-code-sync/*',
            'category-sync/*',
            'esign/sign/*/api/*',
        ]);

        // web 미들웨어 그룹에 자동 재인증 추가
        $middleware->appendToGroup('web', [
            \App\Http\Middleware\AutoLoginViaRemember::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // HTMX/AJAX 요청 시 JSON 에러 응답 반환
        $exceptions->render(function (Throwable $e, Request $request) {
            if ($request->header('HX-Request') || $request->expectsJson() || $request->ajax()) {
                $statusCode = method_exists($e, 'getStatusCode') ? $e->getStatusCode() : 500;

                return response()->json([
                    'success' => false,
                    'message' => $e->getMessage() ?: '서버 오류가 발생했습니다.',
                    'exception' => config('app.debug') ? get_class($e) : null,
                ], $statusCode);
            }

            return null; // 기본 핸들러로 위임
        });
    })->create();
