require_relative "query_spec_helper"
RSpec.describe Card::Query::SqlStatement do
  include QuerySpecHelper

  describe "limit and offset" do
    it "returns limit" do
      expect(run_query(part: "A", limit: 5).size).to eq(5)
    end

    it "does not break if offset but no limit" do
      expect(run_query(part: "A", offset: 5)).not_to eq(0)
    end

    it "does not break count" do
      expect(Card.count_by_cql({ match: "two", offset: 1 }))
        .to eq(cards_matching_two.length)
    end
  end

  describe "trash handling" do
    it "does not find cards in the trash" do
      Card["A+B"].delete!
      expect(run_query(left: "A").sort).to eq(["A+C", "A+D", "A+E"].sort)
    end
  end

  describe "permissions" do
    it "does not find cards not in group" do
      Card::Auth.as_bot do
        Card.create name: "C+*self+*read", type: "Pointer", content: "[[R1]]"
      end
      expect(run_query(plus: "A")).to eq(%w[B D E F])
    end

    context "when nested" do
      it "are generated by default" do
        perm_count = 0
        sql = Card::Query.new(left: { name: "X" }).sql
        sql.scan(/read_rule_id IN \([\d,]+\)/) do
          perm_count += 1
        end
        expect(perm_count).to eq(2)
      end
    end
  end
end
