# frozen_string_literal: true

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

module Litany
  class NetworkLoadBalancer < Resource
    include Taggable

    cfn_type 'AWS::ElasticLoadBalancingV2::LoadBalancer'
    parent_resource :service

    flag :internal, false, inherited: true
    flag :dualstack, false, inherited: true

    property :deletion_protection, false, [true, false]
    property :idle_timeout, 60, [1..3600], inherited: true

    resource_collection NetworkLoadBalancerListener, :listener, required: false
    resource_collection NetworkLoadBalancerTargetGroup, :target_group, required: false
    resource_collection CloudWatchAlarm, :cloudwatch_alarm, required: false
    resource_collection DNSAlias, :dns_alias, required: false

    def add_alias(name, zone)
      load_balancer = self
      domain_name = name == :'@' ? zone : "#{name}.#{zone}"
      dns_alias domain_name do
        target load_balancer
        zone zone
      end
    end

    def add_listener(name, port:, target_port: nil, health_check_path: nil)
      listener(name).port port
      listener(name).protocol :tcp
      listener(name).target_group :"#{name}"

      target_group(name).port target_port || port
      target_group(name).protocol :tcp
      target_group(name).health_check_path health_check_path unless health_check_path.nil?

      return listener(name), target_group(name)
    end

    def prevent_delete
      deletion_protection true
    end

    def properties
      # Not Implementing: Name

      props = {
        Scheme: internal? ? :internal : :'internet-facing',
        Subnets: ref(service.vpc.subnets),
        IpAddressType: dualstack? ? :dualstack : :ipv4,
        Type: :network
      }

      props[:LoadBalancerAttributes] = [{Key: 'deletion_protection.enabled', Value: 'true'}] if deletion_protection

      props
    end

    def default_tags
      {
        LitanyNLBName: name
      }
    end
  end
end
