# frozen_string_literal: true

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

module Litany
  class CloudFrontCacheBehavior < MetaResource
    parent_resource :cloudfront

    property :allow_methods, :read, [:read, :write, :basic_read], inherited: true
    property :cache_methods, :read, [:read, :basic_read], inherited: true
    property :certificate_arn, nil, [String, nil], inherited: true
    property :compress_cache, true, [true, false], inherited: true
    property :default_ttl, 86_400, Integer, inherited: true
    property :max_ttl, 31_536_000, Integer, inherited: true
    property :min_ttl, 0, Integer, inherited: true
    property :viewer_protocol, :redirect_to_https, [:allow_all, :https_only, :redirect_to_https], inherited: true

    property_collection :forward_cookie, [], [String], required: false, inherited: true
    property_collection :forward_header, [], [String], required: false, inherited: true
    property_collection :query_string_cache_key, [], [String], required: false, inherited: true

    def method_set(set)
      case set
        when :read
          [:HEAD, :GET, :OPTIONS]
        when :basic_read
          [:HEAD, :GET]
        when :write
          [:HEAD, :GET, :OPTIONS, :DELETE, :PATCH, :POST, :PUT]
      end
    end

    def to_json(*args)
      data = {
        AllowedMethods: method_set(allow_methods),
        CachedMethods: method_set(cache_methods),
        Compress: compress_cache,
        DefaultTTL: default_ttl,
        ForwardedValues: {
          QueryString: set_query_string_cache_keys?
        },
        MaxTTL: max_ttl,
        MinTTL: min_ttl,
        PathPattern: name,
        TargetOriginId: :default,
        ViewerProtocolPolicy: viewer_protocol.tr('_', '-')
      }

      data[:ForwardedValues][:Cookies] = {Forward: :whitelist, WhitelistedNames: forward_cookies} if set_forward_cookies?
      data[:ForwardedValues][:Headers] = forward_headers if set_forward_headers?
      data[:ForwardedValues][:QueryStringCacheKeys] = query_string_cache_keys if set_query_string_cache_keys?

      data.to_json(*args)
    end
  end
end
