<?php

use App\Http\Middleware\AdminAccess;
use App\Http\Middleware\AdminOuParceiro;
use App\Http\Middleware\ForceJsonResponse;
use App\Http\Middleware\SomenteAdmin;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
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 {
        $middleware->alias([
            'admin.access' => AdminAccess::class,
            'admin.ou.parceiro' => AdminOuParceiro::class,
            'somente.admin' => SomenteAdmin::class,
        ]);

        // Forçar Accept: application/json em todas as rotas /api/*
        $middleware->api(prepend: [
            ForceJsonResponse::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // Resposta padronizada para erros de validação
        $exceptions->render(function (ValidationException $e, Request $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'data' => null,
                    'message' => 'Os dados informados são inválidos.',
                    'errors' => $e->errors(),
                ], 422);
            }
        });

        // Resposta padronizada para não autenticado
        $exceptions->render(function (AuthenticationException $e, Request $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'data' => null,
                    'message' => 'Não autenticado.',
                    'errors' => null,
                ], 401);
            }
        });

        // Resposta padronizada para recurso não encontrado
        $exceptions->render(function (NotFoundHttpException $e, Request $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'data' => null,
                    'message' => 'Recurso não encontrado.',
                    'errors' => null,
                ], 404);
            }
        });
    })->create();
