module Youtube
  class VideoUploadService
    class Error < StandardError; end

    def initialize(team, youtube_channel: nil)
      @team = team
      @resolver = CredentialResolver.new(team, channel: youtube_channel)
      @credential = @resolver.resolve
    end

    def upload_file!(file_path:, title:, description: nil, privacy_status: "unlisted", tags: [])
      return mock_upload if @credential.blank? || missing_oauth_config?
      raise Error, "File non trovato" unless File.exist?(file_path)

      client = authorized_client
      video = Google::Apis::YoutubeV3::Video.new(
        snippet: Google::Apis::YoutubeV3::VideoSnippet.new(
          title: title,
          description: description,
          tags: tags.presence
        ),
        status: Google::Apis::YoutubeV3::VideoStatus.new(
          privacy_status: privacy_status,
          self_declared_made_for_kids: false
        )
      )

      result = client.insert_video(
        "snippet,status",
        video,
        upload_source: file_path,
        content_type: "video/mp4"
      )
      {
        video_id: result.id,
        watch_url: "https://www.youtube.com/watch?v=#{result.id}"
      }
    rescue Google::Apis::Error => e
      raise Error, e.message
    end

    private

    def mock_upload
      id = "mock_vod_#{SecureRandom.hex(6)}"
      { video_id: id, watch_url: "https://www.youtube.com/watch?v=#{id}" }
    end

    def missing_oauth_config?
      ENV["YOUTUBE_CLIENT_ID"].blank?
    end

    def authorized_client
      OauthRefresh.new(@credential).apply!(Google::Apis::YoutubeV3::YouTubeService.new)
    end
  end
end
