<?php

namespace App\Browser\Jobs\InstagramRepost;

use App\Models\JobArtifact;
use App\Models\JobRun;
use App\Notification\Notifications\JobDebugNotification;
use App\Notification\Providers\AllNotification;
use Illuminate\Support\Facades\Log;
use YoutubeDl\Options;
use YoutubeDl\YoutubeDl;

class YTDLPDownloader implements IInstagramVideoDownloader
{
    /**
     * @inheritDoc
     */
    public function downloadVideo(int $jobId, JobRun $jobRun, string $postUrl, string $downloadFolder, string $accountEmail, string $accountPassword): ?YTDLPVideo
    {
        $dl = new YoutubeDl();
        $options = Options::create()
            ->downloadPath($downloadFolder)
            ->apLogin($accountEmail, $accountPassword)
            ->checkAllFormats(true)
            //->format('bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]') // TODO allow downloading audio and video separately and then merging them
            ->format('best[ext=mp4]')
            ->url($postUrl);

        try {
            $videosCollection = $dl->download($options);
            foreach ($videosCollection->getVideos() as $video) {
                if ($video->getError() !== null) {
                    $jobRun->addArtifact(new JobArtifact([
                        "name" => "Erreur lors du téléchargement de la vidéo \"{$video->getTitle()}\"",
                        "content" => $video->getError(),
                    ]));
                    Log::error("Error downloading video: " . $video->getError());
                    return null; // Return null if there was an error downloading the video
                } else {
                    $IVideo = new YTDLPVideo(
                        $video->getWebpageUrl(),
                        $video->getTitle(),
                        $video->getDescription() ?? "",
                        $video->getUploadDate(),
                        $video->getFilename(),
                    );

                    return $IVideo; // Return the video object if download was successful
                }
            }
        } catch (\Exception $e) {
            AllNotification::send(new JobDebugNotification($jobId, "Error while downloading video: " . $e->getMessage()));
            return null;
        }
    }
}
