module Recordings
  class DownloadUrl
    class NotAllowed < StandardError; end

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

    def call
      raise NotAllowed, "Download non disponibile per questo piano" unless download_allowed?
      raise ArgumentError, "Replay non pronto" unless @recording.ready?
      raise ArgumentError, "File non disponibile" if @recording.storage_key.blank?

      "#{MatchLiveTv.app_public_url.chomp('/')}/replay/#{@recording.stream_session_id}/download"
    end

    private

    def download_allowed?
      ent = @recording.team.entitlements
      return false unless ent.phone_download_enabled?

      policy = Recordings::AccessPolicy.new(@recording, viewer: @viewer)
      policy.allowed? || policy.manage_allowed?
    end
  end
end
