# frozen_string_literal: true

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

module Litany
  class Subnet < Resource
    include Taggable

    cfn_type 'AWS::EC2::Subnet'
    parent_resource :vpc

    child_resource RouteTable, :route_table

    output

    property :cidr, nil, [String, NetAddr::CIDR] do |cidr_block|
      cidr_obj = NetAddr::CIDR.create(cidr_block)
      raise "Cidr #{cidr_block} is invalid.  Calculated #{cidr_obj} as start of range." unless cidr_block == cidr_obj.to_s
      cidr_obj
    end
    property :public_ips, true, [true, false]
    property :zone, nil, [String, Symbol] do |value|
      value.to_s.gsub('_', '-').to_sym
    end

    def finalize_resource
      route_table.add_route :default, cidr: '0.0.0.0/0', target: vpc.internet_gateway
    end

    def properties
      {
        AvailabilityZone: zone,
        CidrBlock: cidr,
        MapPublicIpOnLaunch: public_ips,
        VpcId: ref(vpc)
      }
    end
  end
end