# frozen_string_literal: true

require 'litany/resource'

module Litany
  class DNSRecord < Resource
    cfn_type 'AWS::Route53::RecordSet'

    property :comment, nil, [nil, String]
    property :record_name, nil, [nil, String]
    property :type, nil, [:a, :aaaa, :cname, :mx, :naptr, :ptr, :spf, :srv, :txt]
    property :ttl, 60, 0..2_147_483_647

    property_collection :target, [], String

    resource_reference Route53Zone, :zone, required: false
    resource_reference DNSZoneReference, :zone_reference, required: false

    validator :zone_config do
      raise 'You may not set both `zone` and `zone_reference`.' if set_zone? && set_zone_reference?
      raise 'You must set either `zone` or `zone_reference`.' unless set_zone? || set_zone_reference?
    end

    def properties
      _name = record_name || name
      _name = _name.to_s.end_with?('.') ? _name : "#{_name}."

      props = {
        HostedZoneId: ref(zone || zone_reference.id),
        Name: _name,
        ResourceRecords: targets,
        TTL: ttl,
        Type: type.upcase
      }

      props[:Comment] = comment if set_comment?

      props
    end
  end
end
