<?php

use App\Models\AuditLog;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        // Aliasهای فاز ۱
        $middleware->alias([
            'role' => \App\Http\Middleware\EnsureUserHasRole::class,
            'coach.approved' => \App\Http\Middleware\EnsureCoachIsApproved::class,
            'active.account' => \App\Http\Middleware\EnsureAccountIsActive::class,
        ]);

        // Middlewareهای Global — فاز ۱۴ (هدر امنیتی) و فاز ۱۵ (وضعیت آنلاین)
        $middleware->append(\App\Http\Middleware\SecurityHeaders::class);
        $middleware->append(\App\Http\Middleware\TrackLastSeen::class);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        // فاز ۱۶ — Logging تلاش‌های ناموفق دسترسی (بند ۶۰: Permission)
        $exceptions->reportable(function (AuthorizationException $e) {
            if (auth()->check()) {
                AuditLog::record('permission.denied', newValues: [
                    'url' => request()->fullUrl(),
                    'method' => request()->method(),
                    'message' => $e->getMessage(),
                ]);
            }
        });
    })->create();
