# frozen_string_literal: true

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

module Litany
  class Certificate < Resource
    include Taggable

    cfn_type 'AWS::CertificateManager::Certificate'
    id_validator /^arn:aws:acm:[\w-]+-\d:\d+:[\w-]+\/[0-9a-f-]{36}$/

    child_resource CertificateDomainName, :domain_name
    output

    flag :dns_validation, false
    resource_collection CertificateDomainName, :alternate_name, required: false

    def alt(name, validation_name = nil)
      alternate_name "#{self.name}_#{name}" do
        domain name
        validation_domain validation_name
      end
    end

    def domain(name, validation_name = nil)
      domain_name do
        domain name
        validation_domain validation_name
      end
    end

    def properties
      props = {
        DomainName: domain_name.domain
      }

      props[:SubjectAlternativeNames] = alternate_names.collect { |alt| alt.domain } unless alternate_names.empty?

      if dns_validation?
        props[:ValidationMethod] = :DNS
      else
        validation = validation_options
        props[:DomainValidationOptions] = validation unless validation.empty?
      end

      props
    end

    def validation_options
      domains = [domain_name] + alternate_names
      domains = domains.select { |domain| !domain.validation_domain.nil? || domain.domain.count('.') > 1 }

      domains.collect do |domain|
        {
          DomainName: domain.domain,
          ValidationDomain: domain.validation_domain || domain.domain.split('.')[-2..-1].join('.')
        }
      end
    end
  end
end
