# frozen_string_literal: true

require 'litany/mixins'
require 'litany/resource'

module Litany
  class SNSSubscription < Resource
    cfn_type 'AWS::SNS::Subscription'

    parent_resource :topic

    property :endpoint, nil, [Hash, String, nil]
    property :protocol, nil, [:http, :https, :email, :'email-json', :sms, :sqs, :application, :lambda, nil]

    resource_reference SQSQueue, :sqs_endpoint, required: false

    validator :sqs_configuration do
      raise 'You must specify either an `endpoint` and a `protocol` or a `sqs_endpoint`.' unless set_sqs_endpoint? || (set_endpoint? && set_protocol?)
      raise 'You may not specify both an `endpoint` and `protocol` combination as well as a `sqs_endpoint`.' if set_sqs_endpoint? && (set_endpoint? || set_protocol?)
    end


    def properties
      {
        TopicArn: ref(topic),
        Endpoint: set_sqs_endpoint? ? ref(sqs_endpoint, :Arn) : endpoint,
        Protocol: set_sqs_endpoint? ? :sqs : protocol
      }
    end

    def sanitized_name
      "#{topic.name}_#{name}"
    end
  end
end
