# frozen_string_literal: true

module ActiveRecord
  module Tenanted
    module DatabaseConfigurations
      class TenantConfig < ActiveRecord::DatabaseConfigurations::HashConfig
        def tenant
          configuration_hash.fetch(:tenant)
        end

        def new_connection
          ensure_database_directory_exists # adapter doesn't handle this if the database is a URI
          super.tap { |conn| conn.tenant = tenant }
        end

        def tenanted_config_name
          configuration_hash.fetch(:tenanted_config_name)
        end

        def primary?
          ActiveRecord::Base.configurations.primary?(tenanted_config_name)
        end

        def schema_dump(format = ActiveRecord.schema_format)
          if configuration_hash.key?(:schema_dump) || primary?
            super
          else
            "#{tenanted_config_name}_#{schema_file_type(format)}"
          end
        end

        def default_schema_cache_path(db_dir = "db")
          if primary?
            super
          else
            File.join(db_dir, "#{tenanted_config_name}_schema_cache.yml")
          end
        end

        def database_path
          configuration_hash[:database_path]
        end

        private
          def ensure_database_directory_exists
            return unless database_path

            database_dir = File.dirname(database_path)
            unless File.directory?(database_dir)
              FileUtils.mkdir_p(database_dir)
            end
          end
      end
    end
  end
end
