<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Foundation\Configuration\Application as ApplicationConfiguration;
use Illuminate\Filesystem\FilesystemServiceProvider;
use Illuminate\Support\Facades\Facade;
use Illuminate\Console\Scheduling\Schedule;
use App\Services\MicrosoftGraphTokenManager;
use App\Services\OneDriveService;
use Illuminate\Support\Facades\Log;
use \App\Http\Controllers\BudgetItemController;
use Dotenv\Dotenv;

$envFile = '.env.production';
$basePath = dirname(__DIR__); // root project

if (file_exists($basePath . '/' . $envFile)) {
    $dotenv = Dotenv::createImmutable($basePath, $envFile);
    $dotenv->safeLoad();
}
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__ . '/../routes/web.php',
        commands: __DIR__ . '/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->append([
            \Illuminate\Http\Middleware\TrustProxies::class,
            \Illuminate\Http\Middleware\HandleCors::class,
            \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
            \Illuminate\Foundation\Http\Middleware\TrimStrings::class,
        ]);

        $middleware->alias([
            'auth' => \App\Http\Middleware\Authenticate::class,
            'bc.auth' => \App\Http\Middleware\BcAuthMiddleware::class,
            'admin.only' => \App\Http\Middleware\AdminOnly::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
    })

->withSchedule(function (\Illuminate\Console\Scheduling\Schedule $schedule) {

    // DEVELOPMENT — setiap 5 menit
    $schedule->call(function () {
        app(BudgetItemController::class)->storeRawToDatabase();
    })->everyFiveMinutes();

    // PRODUCTION — akhir bulan jam 20:00
    $schedule->call(function () {
        app(BudgetItemController::class)->storeRawToDatabase();
    })->monthlyOn(
        now()->endOfMonth()->day,
        '20:00'
    );

    // ===============================
    // PRODUCTION — Awal bulan (1 hari bulan, 20:00)
    // ===============================
    $schedule->call(function () {
        app(BudgetItemController::class)->storeRawToDatabaseFromScheduler();
    })->monthlyOn(
        1,
        '20:00'
    );

})

    
    ->create();