<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\Integrations\OktaDirectoryIntegration;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use App\Models\CronJob;

class OktaDirectorySpecificRange extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'OktaDirectorySpecificRange:run {date*}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fetch data from Okta directory between time interval';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(protected OktaDirectoryIntegration $oktaDirectoryIntegration)
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //Get the Arguments from the artisan commands
        $arguments = $this->arguments();
        $dateFinal = $arguments['date'][0];
        $this->info("Import Started.");
        $startTime = Carbon::now()->format('Y-m-d H:i:s');
        $dateFrom = Carbon::createFromFormat('m-d-Y-H:i', $dateFinal);
        $dateEnd = Carbon::now();
        $dateTo = Carbon::createFromFormat('m-d-Y-H:i', $dateFinal);
        do {

            $count = 0;
            $dateTo->addDay();
            $this->info("Fetching Data From API Started.");
            $count = $this->oktaDirectoryIntegration->importOktaDirectoryData($dateFrom, $dateTo);

            $this->info("Count of updated employees for " . $dateTo . " " . $count);
            $dateFrom->addDay();
            $this->updateCronJob($startTime, $dateFrom, $dateTo);
            sleep(1);
        } while ($dateTo <= $dateEnd);
    }

    /**
     * Update current api call details in the cron table
     *
     * @return void
     */
    public function updateCronJob($startTime, $dateFrom, $dateTo)
    {
        $cronData = [
            'action' => 'okta_directory',
            'started_at' => $startTime,
            'ended_at' => Carbon::now(),
            'date_from' => $dateFrom,
            'date_to' => $dateTo,
        ];
        CronJob::create($cronData);
    }
}
