<?php

namespace App\Jobs\Exports;

use App\Models\FileExport;
use Facades\App\Services\ExportManagement\ExportManagementService;
use Facades\App\Services\user\UserData;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class UserExportJob 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' => 'Users', 'user_id' => $this->userId, 'report_type' => 'user_report'];
        $reportId = FileExport::create($reportData)->id;
        $filteredData = UserData::getExportUsers($this->request);

        $data = [];
        $datas = collect();

        $filteredData->chunk(5000, function ($userChunks) use ($data, $datas) {
            $datas->push(UserData::getExportUserData($userChunks, 0, $data));
        });

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