<?php

namespace App\Services;

use Vimeo\Vimeo;

class VimeoService
{
    protected $client;

    public function __construct()
    {
        $this->client = new Vimeo(
            env('VIMEO_CLIENT_ID'),
            env('VIMEO_CLIENT_SECRET'),
            env('VIMEO_ACCESS_TOKEN')
        );
    }

    /**
     * Upload video to Vimeo
     */
    public function uploadVideo($filePath, $title, $description)
    {
        $response = $this->client->upload($filePath, [
            'name' => $title,
            'description' => $description
        ]);

        return $response; // Returns Vimeo video URL
    }

    /**
     * Get all user videos
     */
    public function getVideos()
    {
        return $this->client->request('/me/videos', [], 'GET');
    }

    public function getVideo($video_id)
    {
        return $this->client->request("/videos/{$video_id}", [], 'GET');
    }

    public function getVideoFile($videoId)
    {

        // Fetch the video details from Vimeo
        $response = $this->client->request("/videos/$videoId", [], 'GET');

        if (isset($response['body']['files'])) {
            // Get the direct MP4 link (pick the desired quality if multiple are available)
            $videoUrl = $response['body']['files'][0]['link'];
            return $videoUrl;
        } else {
            return $response;
        }

    }



    /**
     * Delete video from Vimeo
     */
    public function deleteVideo($videoUri)
    {
        return $this->client->request($videoUri, [], 'DELETE');
    }
}
