<?php


namespace App\Jobs;

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\Str;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Http;

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

    public $appData;
    public $logoFile;
    public $setupFile;

    public function __construct(array $appData, ?UploadedFile $logoFile, ?UploadedFile $setupFile)
    {
        $this->appData = $appData;
        $this->logoFile = $logoFile;
        $this->setupFile = $setupFile;
    }

    public function handle()
    {
        $logo_name = null;
        $file_name = null;

        if ($this->logoFile) {
            $logo_name = Str::uuid() . '.' . $this->logoFile->getClientOriginalExtension();
            $this->logoFile->storeAs('img', $logo_name, 'public');
        }

        if ($this->setupFile) {
            $file_name = Str::uuid() . '.' . $this->setupFile->getClientOriginalExtension();
            $this->setupFile->storeAs('setups', $file_name, 'public');
        }

        // Aqui você chamaria a API ou salva no DB
        $this->appData['app_logo'] = $logo_name;
        $this->appData['app_address_link_to_download'] = $file_name;

        // Exemplo: chamar a API
        Http::withHeaders([
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . session('access_token'),
        ])->post("{$this->appData['api_base_url']}/applications", $this->appData);
    }
}
