# frozen_string_literal: true

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

module Litany
  class Beanstalk < MetaResource
    include ServiceRoot
    include Stack
    include Taggable

    child_resource BeanstalkApplication, :application
    child_resource IAMRole, :service_role

    flag :instance_crosstalk, false
    flag :internal, false

    property :application_name, nil, [nil, String, Symbol]
    property :cluster_size, 2, [Integer, Range]
    property :description, '', String
    property :device_prefix, 'sd', ['sd', 'xvd']
    property :health_check_path, '/', [String]
    property :instance_type, nil, [nil, String]
    property :log_retention, 365, [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653]
    property :max_version_count, 5, 1..1000
    property :root_volume_size, 50, 4..16_384
    property :stack_name, nil, [nil, proc { BeanstalkEnvironment.stack_mapping.keys }]

    resource_collection AutoScalingVolume, :volume, required: false
    resource_collection SecurityGroup, :security_group, required: false

    resource_reference Certificate, :certificate, required: false
    resource_reference VPC, :vpc

    def beanstalk_environment(env_name, &block)
      app_name = set_application_name? ? application_name : name
      env = application.eb_environment(:"#{app_name}_#{env_name}")
      env.application_name(app_name)
      env.environment_name(env_name)
      env.config(&block)
    end

    def finalize_resource
      service_role.trust service: 'elasticbeanstalk.amazonaws.com'
      service_role.managed_policy('arn:aws:iam::aws:policy/service-role/AWSElasticBeanstalkService')
      service_role.managed_policy('arn:aws:iam::aws:policy/service-role/AWSElasticBeanstalkEnhancedHealth')
    end
  end
end
