module Sessions
  class RegiaAccess
    DEFAULT_TTL = 12.hours

    def initialize(session)
      @session = session
    end

    # Genera un nuovo link (invalida quello precedente).
    def issue_token!
      rotate!
    end

    def rotate!
      token = SecureRandom.urlsafe_base64(24)
      expires = [DEFAULT_TTL.from_now, session_end_cap].compact.min
      @session.update!(
        regia_token_digest: digest(token),
        regia_token_expires_at: expires
      )
      token
    end

    def url(token)
      "#{MatchLiveTv.app_public_url.chomp('/')}/regia/#{token}"
    end

    def self.find_session_by_token(token)
      return if token.blank?

      session = StreamSession.find_by(regia_token_digest: digest(token))
      return unless session
      return if session.regia_token_expires_at.blank? || session.regia_token_expires_at.past?
      return if session.terminal?

      session
    end

    def self.revoke!(session)
      session.update!(regia_token_digest: nil, regia_token_expires_at: nil)
    end

    def self.digest(token)
      Digest::SHA256.hexdigest(token.to_s)
    end

    private

    def token_valid?
      @session.regia_token_digest.present? &&
        @session.regia_token_expires_at&.future? &&
        !@session.terminal?
    end

    def session_end_cap
      return nil unless @session.started_at

      @session.started_at + 8.hours
    end

    def digest(token)
      self.class.digest(token)
    end
  end
end
