# frozen_string_literal: true

require 'litany/resource'
require 'litany/mixins'
module Litany
  class SecurityGroup < Resource
    include Taggable

    cfn_type 'AWS::EC2::SecurityGroup'

    output

    property :description, nil, [String]

    resource_collection SecurityGroupIngress, :ingress_rule, required: false

    def ingress(port:, source:, protocol: :tcp)
      first_port = port.is_a?(Range) ? port.first : port
      last_port = port.is_a?(Range) ? port.last : port
      sources = source.is_a?(Array) ? source : [source]

      sources.each do |source|
        source = source.name if source.is_a?(SecurityGroup)
        source = source.to_s if source.is_a?(NetAddr::CIDR)

        name_parts = ['Allow', protocol]
        name_parts << "Port_#{port}" if first_port == last_port
        name_parts << "Ports_#{first_port}_To_#{last_port}" unless first_port == last_port
        name_parts << "From_#{source.tr('.', '_').tr('/', '_')}"
        name_parts << name
        name = name_parts.join('_')

        ingress_rule name do
          from_port first_port
          protocol protocol
          source source
          to_port last_port
        end
      end
    end

    def properties
      {
        GroupDescription: description,
        VpcId: ref(vpc)
      }
    end

    def vpc
      parent_resource.is_a?(VPC) ? parent_resource : parent_resource.vpc
    end

    def default_tags
      {
        LitanySGName: self.name
      }
    end
  end
end

