<?php

namespace App\Services;

use App\Jobs\GetFileSizeFromCDN;
use App\Models\Downloads;
use App\Models\Episode;
use Illuminate\Http\Request;

class DownloadService
{
    public function createOrUpdateDownloads(Request $request, Episode $episode, int $index): void
    {
        $downloadTypes = [
            'episodedlurl' => 'FHD',
            'episodedlurlinterpolated' => 'FHDi',
            'episodedlurl4k' => 'UHD',
            'downloadUHDi' => 'UHDi',
        ];

        foreach ($downloadTypes as $inputField => $type) {
            $fieldName = $inputField.$index;
            if ($request->filled($fieldName)) {
                $download = Downloads::updateOrCreate([
                    'episode_id' => $episode->id,
                    'type' => $type,
                ], [
                    'url' => $request->input($fieldName),
                ]);

                // Dispatch Job to get File Size from CDN
                GetFileSizeFromCDN::dispatch($download->id);
            }
        }
    }
}
