module Commands
  module V2
    class PutLinkSet < BaseCommand
      def call
        validate!

        content_id = links_params.fetch(:content_id)

        if (link_set = LinkSet.find_by(content_id: content_id))
          link_set.links = link_set.links
            .merge(links_params.fetch(:links))
            .reject {|_, links| links.empty? }

          link_set.save!

          Success.new(links: link_set.links)
        else
          raise CommandError.new(
            code: 404,
            message: "Link set with content_id '#{content_id}' not found"
          )
        end
      end

    private
      def validate!
        raise CommandError.new(
          code: 422,
          message: "Links are required",
          error_details: {
            error: {
              code: 422,
              message: "Links are required",
              fields: {
                links: ["are required"],
              }
            }
          }
        ) unless links_params[:links].present?
      end

      def links_params
        payload
      end
    end
  end
end

module Commands
  module V2
    class PutLinkSet < BaseCommand
      def call
        validate!

        content_id = link_params.fetch(:content_id)

        link_set = LinkSet.find_or_initialize_by(content_id: content_id)

        link_set.links = link_set.links
          .merge(link_params.fetch(:links))
          .reject {|_, links| links.empty? }

        link_set.save!

        Success.new(links: link_set.links)
      end

    private
      def validate!
        raise CommandError.new(
          code: 422,
          message: "Links are required",
          error_details: {
            error: {
              code: 422,
              message: "Links are required",
              fields: {
                links: ["are required"],
              }
            }
          }
        ) unless link_params[:links].present?
      end

      def link_params
        payload
      end
    end
  end
end

Allow the creation of linksets without a content item.
Allow the creation of linksets without a content item.

We can only currently speculate about the exact
workflows, i.e. whether links might be sent to the
publishing API before the main content item.

Since we don't have a confirmed need for constraining
the order of the pushes, we've opted to leave the
system open (and wrote less code in the process).