# typed: true
# frozen_string_literal: true

require "livecheck/strategy"

RSpec.describe Homebrew::Livecheck::Strategy::Json do
  subject(:json) { described_class }

  let(:http_url) { "https://brew.sh/blog/" }
  let(:non_http_url) { "ftp://brew.sh/" }
  let(:regex) { /^v?(\d+(?:\.\d+)+)$/i }
  let(:content) do
    <<~JSON
      {
        "versions": [
          { "version": "1.1.2" },
          { "version": "1.1.2b" },
          { "version": "1.1.2a" },
          { "version": "1.1.1" },
          { "version": "1.1.0" },
          { "version": "1.1.0-rc3" },
          { "version": "1.1.0-rc2" },
          { "version": "1.1.0-rc1" },
          { "version": "1.0.x-last" },
          { "version": "1.0.3" },
          { "version": "1.0.3-rc3" },
          { "version": "1.0.3-rc2" },
          { "version": "1.0.3-rc1" },
          { "version": "1.0.2" },
          { "version": "1.0.2-rc1" },
          { "version": "1.0.1" },
          { "version": "1.0.1-rc1" },
          { "version": "1.0.0" },
          { "version": "1.0.0-rc1" },
          { "other": "version is omitted from this object for testing" }
        ]
      }
    JSON
  end
  let(:content_simple) { '{"version":"1.2.3"}' }
  let(:matches) do
    {
      content: ["1.1.2", "1.1.1", "1.1.0", "1.0.3", "1.0.2", "1.0.1", "1.0.0"],
      simple:  ["1.2.3"],
    }
  end

  describe "::match?" do
    it "returns true for an HTTP URL" do
      expect(json.match?(http_url)).to be true
    end

    it "returns false for a non-HTTP URL" do
      expect(json.match?(non_http_url)).to be false
    end
  end

  describe "::parse_json" do
    it "returns an object when given valid content" do
      expect(json.parse_json(content_simple)).to be_an_instance_of(Hash)
    end
  end

  describe "::versions_from_content" do
    it "returns an empty array when given a block but content is blank" do
      expect(json.versions_from_content("", regex) { "1.2.3" }).to eq([])
    end

    it "errors if provided content is not valid JSON" do
      expect { json.versions_from_content("not valid JSON") { [] } }
        .to raise_error(RuntimeError, "Content could not be parsed as JSON.")
    end

    it "returns an array of version strings when given content and a block" do
      # Returning a string from block
      expect(json.versions_from_content(content_simple) { |json| json["version"] }).to eq(matches[:simple])
      expect(json.versions_from_content(content_simple, regex) do |json|
        json["version"][regex, 1]
      end).to eq(matches[:simple])

      # Returning an array of strings from block
      expect(json.versions_from_content(content, regex) do |json, regex|
        json["versions"].select { |item| item["version"]&.match?(regex) }
                        .map { |item| item["version"][regex, 1] }
      end).to eq(matches[:content])
    end

    it "allows a nil return from a block" do
      expect(json.versions_from_content(content_simple, regex) { next }).to eq([])
    end

    it "errors on an invalid return type from a block" do
      expect { json.versions_from_content(content_simple, regex) { 123 } }
        .to raise_error(TypeError, Homebrew::Livecheck::Strategy::INVALID_BLOCK_RETURN_VALUE_MSG)
    end
  end

  describe "::find_versions" do
    let(:match_data) do
      base = {
        matches: matches[:content].to_h { |v| [v, Version.new(v)] },
        regex:,
        url:     http_url,
      }

      {
        fetched:        base.merge({ content: }),
        cached:         base.merge({ cached: true }),
        cached_default: base.merge({ matches: {}, cached: true }),
      }
    end

    it "finds versions in fetched content" do
      allow(Homebrew::Livecheck::Strategy).to receive(:page_content).and_return({ content: })

      expect(json.find_versions(url: http_url, regex:) do |json, regex|
        json["versions"].select { |item| item["version"]&.match?(regex) }
                        .map { |item| item["version"][regex, 1] }
      end).to eq(match_data[:fetched])
    end

    it "finds versions in content using a block" do
      expect(json.find_versions(url: http_url, regex:, content:) do |json, regex|
        json["versions"].select { |item| item["version"]&.match?(regex) }
                        .map { |item| item["version"][regex, 1] }
      end).to eq(match_data[:cached])

      # NOTE: A regex should be provided using the `#regex` method in a
      #       `livecheck` block but we're using a regex literal in the
      #       `strategy` block here simply to ensure this method works as
      #       expected when a regex isn't provided.
      expect(json.find_versions(url: http_url, content:) do |json|
        regex = /^v?(\d+(?:\.\d+)+)$/i
        json["versions"].select { |item| item["version"]&.match?(regex) }
                        .map { |item| item["version"][regex, 1] }
      end).to eq(match_data[:cached].merge({ regex: nil }))
    end

    it "errors if a block is not provided" do
      expect { json.find_versions(url: http_url, content:) }
        .to raise_error(ArgumentError, "Json requires a `strategy` block")
    end

    it "returns default match_data when url is blank" do
      expect(json.find_versions(url: "", regex:, content:) { "1.2.3" })
        .to eq(match_data[:cached_default].merge({ url: "" }))
    end

    it "returns default match_data when content is blank" do
      expect(json.find_versions(url: http_url, regex:, content: "") { "1.2.3" })
        .to eq(match_data[:cached_default])
    end
  end
end
