<?php

namespace App\Jobs\Exports;

use App\Models\FileExport;
use Facades\App\Services\ExportManagement\ExportManagementService;
use Facades\App\Services\Reports\Generator;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class ExportReport implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Request object
     * 
     * @var Illuminate\Http\Request;
     */
    private $request;

    /**
     * The user id.
     * 
     * @var integer
     */
    private $userId;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(array $request)
    {
        $this->request =  $request;
        $this->userId =  auth()->user()->id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();

        $reportData = ['report_name' => 'Report Generator', 'user_id' => $this->userId, 'report_type' => 'generator_report'];
        $reportId = FileExport::create($reportData)->id;
        $assetData = Generator::exportData($this->request);

        $data = [];
        $datas = collect();
        $chunkSize = 5000;
        $index = 0;
        $assetData->chunk($chunkSize, function ($assetsChunks) use ($data, $datas, &$index, $chunkSize) {
            $datas->push(Generator::getExportAssetData($assetsChunks, $index, $data));
            $index = $index + $chunkSize;
        });

        $filename =  ExportManagementService::exportForLater($datas->toArray());
        $reportUpdateData = ['report_url' => $filename];
        FileExport::where("id", $reportId)->update($reportUpdateData);
    }
}
