# frozen_string_literal: true

require 'semver_dialects/commands/sort_versions'

RSpec.describe SemverDialects::Commands::SortVersions do
  let(:output) { StringIO.new }
  let(:type) { 'go' }
  let(:options) { {} }

  describe 'execute' do
    context 'with valid versions' do
      it 'sorts versions correctly' do
        versions = ['1.2', '2.0', '1.1']
        command = described_class.new(type, versions, options)

        command.execute(output:)

        expect(output.string).to eq("Sorted versions: 1.1, 1.2, 2.0\n")
      end
    end

    context 'with invalid versions' do
      it 'sorts valid versions and reports invalid ones' do
        versions = ['1.2', 'invalid', '2.0']
        command = described_class.new(type, versions, options)

        command.execute(output:)

        expect(output.string).to include("Warning: Invalid version 'invalid'")
        expect(output.string).to include('Sorted versions: 1.2, 2.0')
      end
    end

    context 'with JSON output option' do
      let(:options) { { json: true } }

      it 'outputs sorted versions in JSON format' do
        versions = ['1.2', 'invalid', '2.0']
        command = described_class.new(type, versions, options)

        command.execute(output:)

        json_output = JSON.parse(output.string)
        expect(json_output['versions']).to eq(['1.2', '2.0'])
        expect(json_output['invalid']).to eq(['invalid'])
      end
    end

    context 'with unsupported package type' do
      it 'raises an UnsupportedPackageTypeError' do
        versions = ['1.0']
        command = described_class.new('unsupported', versions, options)

        expect do
          command.execute(output:)
        end.to raise_error(SemverDialects::UnsupportedPackageTypeError)
      end
    end

    context 'with unsupported versions' do
      let(:type) { 'apk' }

      it 'sorts valid versions and reports unsupported ones' do
        versions = ['1.2.3', '01.2.3', '2.0.0']
        command = described_class.new(type, versions, options)

        command.execute(output:)

        expect(output.string).to include("Warning: Invalid version '01.2.3' - unsupported version '01.2.3'")
        expect(output.string).to include('Sorted versions: 1.2.3, 2.0.0')
      end
    end
  end
end
