<?php

namespace Inside\BCLH\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;
use Inside\BCLH\Events\BulkCSVGeneratedEvent;
use Inside\BCLH\Events\BulkExcelGeneratedEvent;
use Inside\BCLH\Exports\SopsExport;

class ExportSopsInExcel implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    public const EXCEL_DOWNLOAD_FOLDER = 'excel/download';

    protected string $userUuid;

    protected array $contents;

    public function __construct(string $userUuid, array $contents)
    {
        $this->userUuid = $userUuid;
        $this->contents = $contents;
    }

    public function handle(): void
    {
        Storage::disk('protected')->makeDirectory(self::EXCEL_DOWNLOAD_FOLDER);

        $filePath = self::EXCEL_DOWNLOAD_FOLDER.'/'.$this->userUuid.'-'.date('YmdHis').'.xlsx';

        (new SopsExport($this->contents))->store($filePath, 'protected');

        event(new BulkCSVGeneratedEvent($this->userUuid, $filePath));

        $this->delete();
    }
}
