# frozen_string_literal: true

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

module Litany
  class SecurityGroupIngress < Resource
    cfn_type 'AWS::EC2::SecurityGroupIngress'

    property :from_port, nil, [Integer]
    property :protocol, nil, [:tcp, :udp, :icmp]
    property :source, nil, [String, NetAddr::CIDR, SecurityGroup, Symbol] do |source|
      case source
        when Symbol
          SecurityGroup.new(source) unless source == :apll
        when String
          unless source.start_with?('pl-')
            cidr_obj = NetAddr::CIDR.create(source)
            raise "Cidr #{source} is invalid.  Calculated #{cidr_obj} as start of range." unless source == cidr_obj.to_s || "#{source}/32" == cidr_obj.to_s
            cidr_obj
          end
      end
    end
    property :to_port, nil, [Integer]

    resource_reference SecurityGroup, :security_group, required: false

    def properties
      props = {
        FromPort: from_port,
        GroupId: ref(security_group || parent_resource),
        IpProtocol: protocol,
        ToPort: to_port
      }

      case source
        when NetAddr::CIDRv4
          props[:CidrIp] = source
        when NetAddr::CIDRv6
          props[:CidrIpv6] = source
        when SecurityGroup
          props[:SourceSecurityGroupId] = ref(source)
        when String
          props[:SourcePrefixListId] = source
        when :apll
          props[:SourcePrefixListId] = apll_amazon_corp
        # SourceSecurityGroupOwnerId Can be set if that security group is in another account.  Not currently implemented.
      end

      props
    end

    def apll_amazon_corp
      case active_environment.region.to_s
      when 'ap-northeast-1'
        'pl-bea742d7'
      when 'ap-northeast-2'
        'pl-8fa742e6'
      when 'ap-south-1'
        'pl-f0a04599'
      when 'ap-southeast-1'
        'pl-60a74209'
      when 'ap-southeast-2'
        'pl-04a7426d'
      when 'ca-central-1'
        'pl-85a742ec'
      when 'eu-central-1'
        'pl-19a74270'
      when 'eu-north-1'
        'pl-c2aa4fab'
      when 'eu-west-1'
        'pl-01a74268'
      when 'eu-west-2'
        'pl-fca24795'
      when 'eu-west-3'
        'pl-7dac4914'
      when 'sa-east-1'
        'pl-a6a742cf'
      when 'us-east-1'
        'pl-60b85b09'
      when 'us-east-2'
        'pl-3ea44157'
      when 'us-west-1'
        'pl-a4a742cd'
      when 'us-west-2'
        'pl-f8a64391'
      else
        raise "APLL is not yet supported in Litany for region #{active_environment.region}"
      end
    end
  end
end

