<?php

namespace App\Console;

use App\Models\Setting;
use Illuminate\Console\Scheduling\Schedule;
use App\Services\ScheduledBatchReportService;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * Define the application's command schedule.
     */
    protected function schedule(Schedule $schedule): void
    {

        $scheduleTask = $schedule->call(function () {
            (new ScheduledBatchReportService())->runBatch();
        });

        $this->applyInterval($scheduleTask);

    }

    /**
     * Register the commands for the application.
     */
    protected function commands(): void
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }

    /**
     * Applies the appropriate interval for the cron job scheduling based on the configured interval.
     *
     * This method adjusts the cron job schedule based on the current interval defined in the settings.
     * It sets the frequency of job execution to one of the following: every minute, every 5 minutes, every 15 minutes,
     * every 30 minutes, or hourly.
     *
     * @tag srm_schdular
     */
    private function applyInterval($schedule)
    {
        switch ($this->getCurrentInterval()) {
            case 1:
                $schedule->everyMinute();
                break;
            case 5:
                $schedule->everyFiveMinutes();
                break;
            case 15:
                $schedule->everyFifteenMinutes();
                break;
            case 30:
                $schedule->everyThirtyMinutes();
                break;
            case 60:
                $schedule->hourly();
                break;
            default:
                $schedule->everyMinute();
                break;
        }
    }


    /**
     * Retrieves the current interval value from the system settings.
     *
     * This method fetches the scheduling interval defined in the settings table by looking up the key `scheduling_cron_job_interval`.
     * The value is returned as an integer representing the interval in minutes.
     *
     * @tag srm_schdular
     */
    private function getCurrentInterval()
    {
        return Setting::where('settings_key', 'scheduling_cron_job_interval')->first()->settings_value;

    }


}
