require_relative "boot"

require "rails/all"

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

require 'URLcrypt'
require_relative 'middleware/maintenance_mode'

Dotenv::Railtie.load if defined?(Dotenv::Railtie)

module Chaskiq

  module Config

    def self.get(name)
      # config[name] || ENV[name.upcase]
      Rails.application.credentials.config.fetch(
        name.downcase.to_sym, ENV[name.to_s.upcase]
      )
    end
  
    def self.fetch(name, fallback)
      Rails.application.credentials.config.fetch(
        name.downcase.to_sym, ENV.fetch(name.to_s.upcase, fallback)
      )
      # config[name] || ENV.fetch(name.upcase, fallback)
    end
  end


  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 7.0

    # Configuration for the application, engines, and railties goes here.
    #
    # These settings can be overridden in specific environments using the files
    # in config/environments, which are processed later.
    #
    # config.time_zone = "Central Time (US & Canada)"
    # config.eager_load_paths << Rails.root.join("extras")

    config.encoding = 'utf-8'

    config.assets.css_compressor = nil

    config.i18n.fallbacks = [I18n.default_locale]

    config.action_cable.disable_request_forgery_protection = true

    config.active_storage.variant_processor = :mini_magick

    # config.active_support.isolation_level = :fiber

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.

    config.generators do |g|
      g.test_framework :rspec, fixture: false
      # g.orm :active_record, primary_key_type: :uuid
      # g.fixture_replacement :factory_bot, :dir => 'spec/factories'
      g.assets false
      g.helper false
    end

    config.middleware.insert_before 0, Rack::Cors do
      global_cors_domain = Chaskiq::Config.fetch("GLOBAL_CORS_DOMAIN", "*")
      allow do
        origins global_cors_domain
        resource "*", headers: :any, methods: %i[get post put options]
      end
    end

    if Chaskiq::Config::get("MAINTENANCE_MODE") == "true"
      config.middleware.insert_before Rack::Sendfile, Middleware::MaintenanceMode
    end

    URLcrypt.key = [Chaskiq::Config.get('SECRET_KEY_BASE')].pack('H*')

    locales = %w[af sq ar eu bg be ca hr cs da nl en eo et fo fi fr gl de el iw hu is ga it ja ko lv lt mk mt no pl pt ro ru gd sr sr sk sl es sv tr uk zh-CN]
    config.available_locales = locales
    I18n.available_locales = locales
    config.i18n.default_locale = :en

    config.action_dispatch.tld_length = Chaskiq::Config.fetch('TLD_LENGTH', 1)&.to_i

  end
end
