<?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;

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 (Schedule $schedule) {
        //$schedule->call(function () {
        //    file_put_contents(
        //        storage_path('logs/scheduler_heartbeat.log'),
        //        now()->toDateTimeString() . PHP_EOL,
        //        FILE_APPEND
        //    );
        //})->everyMinute();
        
        //->everyMinute()
        //->dailyAt('12:12')
        
        $schedule->call(function () {
            Artisan::call('queue:work', [
                '--queue'           => 'mail,default',
                '--once'            => true,
                '--stop-when-empty' => true,
                '--sleep'           => 1,
                '--tries'           => 3,
                '--timeout'         => 120,
            ]);
        })
        ->everyMinute()
        ->name('queue-once')
        ->withoutOverlapping();
        
        $schedule->call(function () {
            $token = app(MicrosoftGraphTokenManager::class)->getAccessToken();
            $svc   = app(OneDriveService::class);
            $share = config('services.onedrive.hic_share_url');

            $ownerUpn = config('services.onedrive.owner_upn'); 
            $path     = config('services.onedrive.hic_path'); 
    
            $svc->downloadFromUserPath($token, $ownerUpn, $path, 'history_forecast(HIC).txt');

            $share = config('services.onedrive.rbc_share_url');

            $ownerUpn = config('services.onedrive.owner_upn'); 
            $path     = config('services.onedrive.rbc_path'); 
    
            $svc->downloadFromUserPath($token, $ownerUpn, $path, 'history_forecast.txt');

            $share = config('services.onedrive.hin_share_url');

            $ownerUpn = config('services.onedrive.owner_upn'); 
            $path     = config('services.onedrive.hin_path'); 
    
            $svc->downloadFromUserPath($token, $ownerUpn, $path, 'history_forecast(HIND).txt');
            //$upn   = config('services.onedrive.owner_upn');

            // 1) List root (My files)
            //$rootItems = $svc->listUserChildren($token, $upn, '');
            // 2) List Documents
            //$docsItems = $svc->listUserChildren($token, $upn, 'Documents');
            // 3) List Documents/Maintain  (watch out for trailing spaces!)
            //$maintainItems = $svc->listUserChildren($token, $upn, 'Documents/Maintain');
            
            // 4) If you’re not sure of the exact folder or there’s a trailing space, search:
            //$hit = $svc->findUserItemByName($token, $upn, 'history_forecast(HIC).txt');
            // $hit['path'] shows the true parent path you should use for downloadFromUserPath()
        })
        ->dailyAt('08:00')  
        ->timezone('Asia/Makassar')         
        ->name('onedrive:download-hic')  
        ->withoutOverlapping();
    })
    
    ->create();