<?php

namespace App\Console\Commands\Report;

use App\Repositories\ReportRepository;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class ReportCacheDestinationReport extends \App\Console\Commands\BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'report:cache-destination-report';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This serves to cache each organisations list of destination reports.';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        if(env('reporting_disabled')) {
            $this->log_warning("Not running as `reporting_disabled` is set in the .env file.", []);
            return 0;
        }

        if(env('reporting_cache_report_disabled')) {
            $this->log_warning("Not running as `reporting_cache_report_disabled` is set in the .env file.", []);
            return 0;
        }

        // Track start
        $start = microtime(true);

        // Retrieve the admin list then compare it to the stored list. If they're different, onward we go. Otherwise bail out.
        $stored_admin_list = json_decode(Redis::get('report-singular-admin-list'), true);

        if(!$stored_admin_list || !isset($stored_admin_list['data'])) {
            $this->log_warning("Not running as `reporting_cache_report_disabled` is set in the .env file.", []);
            Log::warning('(report:cache-destination-report) No admin list found in cache, aborting.');
            return 0;
        }

        // Reserve repository
        $rr = new ReportRepository();

        foreach($stored_admin_list['data'] as $report) {
            
            $report_id = $report['report_id'];
            $organisation_id = $report['organisation_id'];


            if(Redis::get("report-$organisation_id-$report_id") === null) {
                
                $report_download = $rr->get_report_singular($report_id, $organisation_id);

                if($report_download !== false) {
                    Redis::setex("report-$organisation_id-$report_id", 86400, gzdeflate(base64_encode($report_download), 9) );

                    $this->log_event("Compressed and stored report ID #$report_id for Organisation #$organisation_id", []);
                }
            }

        }

        if(($time_taken = microtime(true) - $start) && $time_taken > 30) {
            $this->log_warning("Execution time exceeded 30 seconds: $time_taken\s", []);
        }

        return 0;
    }
}