<?php

namespace App\Jobs;

use App\Models\Downloads;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Http\Client\RequestException;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

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

    private $downloadId;

    /**
     * Create a new job instance.
     */
    public function __construct(int $id)
    {
        $this->downloadId = $id;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        // Retrieve the download record, return if not found
        $download = Downloads::find($this->downloadId);
        if (! $download) {
            Log::error("Download not found for ID: {$this->downloadId}");

            return;
        }

        // Generate encrypted file path and expiration
        $endpoint = config('hstream.download_domain_4k')[0];
        $serverPath = 'hentai/';
        if ($download->type === 'FHD' || $download->type === 'FHDi') {
            $serverPath = 'hentai-1080p/';
        }

        $file = Crypt::encryptString($serverPath.$download->url);
        $expire = Crypt::encryptString(Carbon::now()->addHours(6)->toDateTimeString());

        try {
            // Send HTTP request to the endpoint
            $response = Http::get($endpoint.'/getSize/'.$file.'/'.$expire);

            // Check if response is successful
            if ($response->successful()) {
                $size = $response->json()['size'];

                // Update the download record with the retrieved size
                $download->size = $size;
                $download->save();

                Log::info("Updated size for download ID: {$this->downloadId}");
            } else {
                Log::error("Failed to retrieve size for download ID: {$this->downloadId}, HTTP status: {$response->status()}");
            }
        } catch (RequestException $e) {
            Log::error("HTTP request failed for download ID: {$this->downloadId}, error: ".$e->getMessage());
        } catch (\Exception $e) {
            Log::error("An error occurred for download ID: {$this->downloadId}, error: ".$e->getMessage());
        }
    }
}
