require "active_support/core_ext/integer/time"

Rails.application.configure do
  config.enable_reloading = false
  config.eager_load = true
  config.consider_all_requests_local = false

  config.active_storage.service = :local

  # Nginx Proxy Manager termina TLS
  config.assume_ssl = true
  config.force_ssl = true
  config.ssl_options = {
    redirect: {
      exclude: ->(request) { request.path == "/up" || request.path == "/cable" }
    }
  }

  config.action_cable.disable_request_forgery_protection = true

  if (cable_url = ENV["CABLE_URL"]).present?
    config.action_cable.url = cable_url
  end

  cable_origins = ENV.fetch("CORS_ORIGINS", "*").split(",").map(&:strip)
  config.action_cable.allowed_request_origins = cable_origins + [
    %r{https?://.*}
  ]

  allowed_hosts = ENV.fetch("ALLOWED_HOSTS", "").split(",").map(&:strip).reject(&:empty?)
  config.hosts = allowed_hosts if allowed_hosts.any?

  config.host_authorization = {
    exclude: ->(request) { request.path == "/up" || request.path.start_with?("/cable") }
  }

  config.logger = ActiveSupport::Logger.new(STDOUT)
    .tap  { |logger| logger.formatter = ::Logger::Formatter.new }
    .then { |logger| ActiveSupport::TaggedLogging.new(logger) }

  config.log_tags = [ :request_id ]
  config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info")

  config.action_mailer.perform_caching = false
  config.action_mailer.default_url_options = {
    host: URI.parse(ENV.fetch("APP_PUBLIC_URL", "https://www.matchlivetv.it")).host,
    protocol: URI.parse(ENV.fetch("APP_PUBLIC_URL", "https://www.matchlivetv.it")).scheme
  }
  config.action_mailer.raise_delivery_errors = true

  if ENV["SMTP_ADDRESS"].present?
    config.action_mailer.delivery_method = :smtp
    config.action_mailer.smtp_settings = {
      address: ENV["SMTP_ADDRESS"],
      port: ENV.fetch("SMTP_PORT", 587).to_i,
      user_name: ENV["SMTP_USERNAME"],
      password: ENV["SMTP_PASSWORD"],
      authentication: ENV.fetch("SMTP_AUTH", "plain"),
      enable_starttls_auto: ENV.fetch("SMTP_STARTTLS", "true") == "true"
    }
  end
  config.i18n.fallbacks = true
  config.active_support.report_deprecations = false
  config.active_record.dump_schema_after_migration = false
  config.active_record.attributes_for_inspect = [ :id ]
end
