<?php

use App\Jobs\CheckAbsenceDays;
use App\Jobs\ChangeLeaveStatus;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Spatie\Permission\Exceptions\UnauthorizedException;
use Spatie\Permission\Middleware\PermissionMiddleware;
use Spatie\Permission\Middleware\RoleMiddleware;
use Spatie\Permission\Middleware\RoleOrPermissionMiddleware;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Support\Facades\Log;

// Helper function to extract permission from exception - define it BEFORE the return statement
if (!function_exists('extractPermissionFromException')) {
    function extractPermissionFromException(UnauthorizedException $e): string
    {
        if (preg_match('/Required (\"|\w+)(.*?)\]/', $e->getMessage(), $matches)) {
            return trim($matches[2], '[]"');
        }
        return 'unknown-permission';
    }
}

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) {
        $middleware->alias([
            'permission' => PermissionMiddleware::class,
            'role' => RoleMiddleware::class,
            'role_or_permission' => RoleOrPermissionMiddleware::class,
        ]);

        $middleware->group('api', [
            \App\Http\Middleware\JwtCookieMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        // You can add exception handling here if needed
    })
    ->withSchedule(function (Schedule $schedule) {
        // First scheduled job
        $schedule->call(function () {
            try {
                dispatch(new CheckAbsenceDays());
            } catch (\Throwable $e) {
                Log::error("Failed to dispatch CheckDailyAbsenceJob: " . $e->getMessage());
            }
        })->everyFiveSeconds();

        // Second scheduled job
        $schedule->call(function () {
            try {
                dispatch(new ChangeLeaveStatus());
            } catch (\Throwable $e) {
                Log::error("Failed to dispatch ChangeLeaveStatus: " . $e->getMessage());
            }
        })->everyFiveSeconds();
    })
    ->create();
