# frozen_string_literal: true

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

module Litany
  class SQSQueuePolicy < Resource
    cfn_type 'AWS::SQS::QueuePolicy'

    parent_resource :queue
    child_resource IAMPolicyDocument, :policy

    def allow(topic:, in_account: { Ref: 'AWS::AccountId' }, region: '*')
      if topic.is_a?(Array)
        topic.each { |t| allow(topic: t, in_account: in_account, region: region) }
        return
      end

      if in_account.is_a?(Array)
        in_account.each { |account| allow(topic: topic, in_account: account, region: region) }
        return
      end

      if region.is_a?(Array)
        region.each { |r| allow(topic: topic, in_account: in_account, region: r) }
        return
      end

      statement = policy.next_statement
      statement.actions 'SQS:SendMessage'
      statement.principal AWS: '*'
      statement.resource ref(queue, :Arn)

      arn = arn_builder(service: :sns, account: in_account, region: region, resource: topic)
      operator = topic.include?('*') || in_account.include?('*') || region.include?('*') ? :ArnLike : :ArnEquals

      statement.condition operator => { 'aws:SourceArn': arn }
    end

    def allow_service(service:, from: nil)
      statement = policy.next_statement
      statement.actions 'sqs:SendMessage'
      statement.allow_principal service: service
      statement.resource ref(queue, :Arn)

      return if from.nil?

      operator = from.respond_to?(:include?) && from.include?('*') ? :ArnLike : :ArnEquals
      statement.condition operator => { 'aws:SourceArn': from }
    end

    def properties
      {
        Queues: [
          ref(queue)
        ],
        PolicyDocument: policy
      }
    end
  end
end
