module Recordings
  class PublishToYoutube
    class Error < StandardError; end

    def initialize(recording, privacy_status: nil)
      @recording = recording
      @privacy_status = privacy_status
    end

    def call
      team = @recording.team
      ent = team.entitlements
      raise Error, "Republicazione YouTube disponibile con Premium Full" unless ent.premium_full? && ent.youtube_enabled?
      raise Error, "Replay già pubblicato su YouTube" if @recording.youtube_video_id.present?
      raise Error, "Replay non pronto" unless @recording.ready?

      video_path = local_video_path
      raise Error, "File video non disponibile in locale; riprova dopo l’upload" unless video_path

      session = @recording.stream_session
      privacy = @privacy_status.presence || youtube_privacy
      channel = session.platform == "youtube" ? "team" : nil

      result = Youtube::VideoUploadService.new(team, youtube_channel: channel).upload_file!(
        file_path: video_path,
        title: @recording.title_or_default,
        description: youtube_description(session),
        privacy_status: privacy,
        tags: %w[MatchLiveTV replay sport]
      )

      meta = @recording.metadata.merge(
        "youtube_publish" => {
          "video_id" => result[:video_id],
          "watch_url" => result[:watch_url],
          "published_at" => Time.current.iso8601,
          "privacy_status" => privacy
        }
      )

      @recording.update!(
        youtube_video_id: result[:video_id],
        youtube_published_at: Time.current,
        metadata: meta
      )
      @recording
    ensure
      FileUtils.rm_f(@temp_video) if @temp_video && File.exist?(@temp_video)
    end

    private

    def local_video_path
      return @temp_video if @temp_video && File.exist?(@temp_video)

      if @recording.storage_key.blank?
        return nil
      end

      storage = Recordings::Storage.new
      path = storage.local_path_for_key(@recording.storage_key)
      return path if path && File.exist?(path)

      @temp_video = storage.download_to_temp(key: @recording.storage_key)
      @temp_video
    end

    def youtube_privacy
      @recording.publicly_listed? ? "public" : "unlisted"
    end

    def youtube_description(session)
      match = session.match
      base = "#{match.team.name} vs #{match.opponent_name}"
      url = @recording.replay_url
      [base, url, "Trasmesso con Match Live TV"].compact.join("\n\n")
    end
  end
end
