# frozen_string_literal: true

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

module Litany
  class Redirects < MetaResource
    include Stack

    parent_resource :project

    resource_collection CloudFrontDistribution, :distribution
    # resource_collection DNSAlias, :dns_alias
    resource_collection S3Bucket, :bucket

    resource_reference Environment, :environment

    validator(:us_east_1) do
      raise 'Redirects must have an environment that has region of `:us_east_1`.' unless set_environment? && environment.region == :'us-east-1'
    end

    def from(domain, to:, zone:, certificate:)
      env = environment

      redirect_bucket = bucket domain do
        # access :public_read
        environment env
        redirect_to to
      end

      distro = distribution domain do
        add_alias domain, zone
        alias_name domain.to_s
        certificate certificate
        default_ttl 60
        max_ttl 60
        min_ttl 60
        origin_url redirect_bucket.website_domain
        origin_protocol_policy :'http-only'
        price_class :'100'
        require_sni
      end
    end
  end
end
