<?php

namespace App\Jobs;

use App\Models\MovieFile;
use FFMpeg\FFMpeg;
use FFMpeg\Format\Video\X264;
use FFMpeg\Coordinate\Dimension;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\File;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Str;

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

    protected $movieFile;
    protected $originalPath;
    protected $originalExtension;
    protected $type;

    public function __construct($movieFile, $originalPath, $originalExtension, $type = null)
    {
        $this->movieFile = $movieFile;
        $this->originalPath = $originalPath;
        $this->originalExtension = $originalExtension;
        $this->type = $type;
    }

    public function handle()
    {
        try {
            // Step 1: Build the folder structure
            $folderName = $this->movieFile->id;
            $folder_name = $this->type ?? 'videos'; // Default to 'movies' if type is not provided
            $basePath = public_path("uploads/".$folder_name."/{$folderName}");

            logger()->info("Processing video to: {$basePath}");

            // Step 2: Create FFMpeg instance
            $ffmpeg = FFMpeg::create([
                'ffmpeg.binaries'  => 'C:\\ffmpeg\\bin\\ffmpeg.exe',
                'ffprobe.binaries' => 'C:\\ffmpeg\\bin\\ffprobe.exe',
                'timeout'          => 3600,
                'ffmpeg.threads'   => 12,
            ]);

            $video = $ffmpeg->open($this->originalPath);

            // Step 3: Define resolutions
            $qualities = [
                'sd' => '640x360',
                'hd' => '1280x720',
                'fullhd' => '1920x1080',
            ];

            foreach ($qualities as $folder => $resolution) {
                $qualityPath = "{$basePath}/{$folder}";
                File::ensureDirectoryExists($qualityPath);

                $outputPath = "{$qualityPath}/video.{$this->originalExtension}";
                [$width, $height] = explode('x', $resolution);

                $format = new X264('libmp3lame', 'libx264');
                $format->setAudioKiloBitrate(128);
                $format->setKiloBitrate(1000);

                try {
                    $video->filters()->resize(new Dimension((int)$width, (int)$height))->synchronize();
                    $video->save($format, $outputPath);
                } catch (\Exception $e) {
                    logger()->error("FFmpeg failed: {$folder}", [
                        'message' => $e->getMessage(),
                        'path' => $outputPath,
                    ]);
                }
            }

            // Step 4: Update movie_files.file_url to HD path
            $relativePath = "uploads/{$folder_name}/{$folderName}/hd/video.{$this->originalExtension}";

            logger()->info("Finished processing job for movieFile ID: {$this->movieFile->id}");
        } catch (\Exception $e) {
            logger()->error('Video conversion failed!', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            throw $e; // To mark job as failed
        }
    }
}
