<?php

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

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 {
        $middleware->alias([
            'unit_admin' => \App\Http\Middleware\UnitAdminMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {

        // ── VALIDATION ERRORS (API) ──
        $exceptions->render(function (\Illuminate\Validation\ValidationException $e, $request) {
            return response()->json([
                'status' => '0',
                'status_code' => '422',
                'message' => 'Validation failed',
                'data' => null,
                'errors' => $e->errors()
            ], 422);
        });

        // ── AUTH REDIRECT (Web) — smart redirect based on URL ──
        $exceptions->render(function (AuthenticationException $e, $request) {
            if (!$request->expectsJson()) {
                if (str_starts_with($request->path(), 'unit-admin')) {
                    return redirect()->route('unit-admin.login');
                }
                return redirect()->route('admin.login');
            }
        });

    })->create();