# frozen_string_literal: true

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

module Litany
  class Volume < Resource
    include Taggable

    cfn_type 'AWS::EC2::Volume'
    parent_resource :instance

    property :device, nil, [String] do |value|
      raise "Invalid value `#{value}` for device.  Examples: `/dev/xvd[b-c][a-z]`." unless value =~ %r/\/dev\/xvd[b-c][a-z]/
      value
    end
    property :encrypted, true, [true, false]
    property :iops, nil, [nil, 100..20_000]
    property :size, nil, 4..16_384
    property :volume_type, :gp2, [:gp2, :io1, :general, :provisioned] do |value|
      map = {general: :gp2, provisioned: :io1}
      map.include?(value) ? map[value] : value
    end

    def properties
      props = {
        AutoEnableIO: false,
        AvailabilityZone: instance.subnet.zone,
        Encrypted: encrypted,
        Size: size,
        VolumeType: volume_type
      }

      unless iops.nil?
        props[:Iops] = iops
        props[:VolumeType] = :io1
      end

      props
    end

    def resource_name
      "#{instance.resource_name}_#{super}".pascal_case.to_sym
    end

    def default_tags
      {
          LitanyVolumeName: self.name,
      }
    end
  end
end
