# frozen_string_literal: true

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

module Litany
  class CloudWatchLogGroup < Resource
    cfn_type 'AWS::Logs::LogGroup'

    property :retention, 731, [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653]

    resource_collection CloudWatchLogMetricFilter, :filter, required: false

    def alarm_on(namespace: nil, metric:, pattern:, threshold: 1, action: nil, &block)
      namespace ||= parent_resource.name.to_s.pascal_case

      alarm_filter = filter(:"#{name}_#{metric.snake_case}")
      alarm_filter.metric(metric)
      alarm_filter.namespace(namespace)
      alarm_filter.pattern pattern

      # Creates a default alarm state that will be overwritten by the provided closure
      alarm = alarm_filter.alarm
      alarm.description("#{namespace}.#{metric} alarm")
      alarm.metric(metric)
      alarm.missing_data(:not_breaching)
      alarm.operator(:greater_than_or_equal_to)
      alarm.statistic(:sum)
      alarm.threshold(threshold)
      alarm.unit(:count)

      alarm.alarm_action(action) unless action.nil?
      alarm.ok_action(action) unless action.nil?

      alarm.config(&block)
    end


    def properties
      {
        LogGroupName: name,
        RetentionInDays: retention
      }
    end
  end
end
