require_relative "s3_client"

module Support
  module EnvFiles
    SHADOW_ENV_FILE = ".env.shadow".freeze
    ENV_FILE = ".env".freeze
    SHADOW_S3_ENV_FILE = Dir.glob("configs/configs_from_s3_*.env.shadow").first
    S3_ENV_FILE = SHADOW_S3_ENV_FILE.sub(".shadow", "")
    S3_BUCKET = "nickelback".freeze
    UPLOADED_S3_ENV_FILE = "cucumber-configs/#{File.basename(S3_ENV_FILE)}".freeze

    class << self
      def load_env_file
        if File.exist? ENV_FILE
          fail(
            "`.env` file is not in sync with the template!\n"\
            "Copy any new keys from `.env.shadow` to `.env` and populate"\
            " them.".color(:red)
          ) unless env_file_matches_shadow(ENV_FILE, SHADOW_ENV_FILE)
        else
          puts(
            "`.env` file does not exist!\n"\
            "Run `rake cucumber:init_dotenv` to create it, and populate the fields"\
            " manually.".color(:red)
          )
        end

        Dotenv.load(ENV_FILE)
      end

      def load_s3_env_file
        return if ENV["LOCAL_ENV"].to_i > 0
        s3_env_files_in_sync =
          s3_env_file_exists? &&
          env_file_matches_shadow(
            S3_ENV_FILE,
            SHADOW_S3_ENV_FILE
          )

        fail(
          "`#{S3_ENV_FILE}` is not in sync with the template!\n"\
          "run `rake cucumber:sync_env`.".color(:red)
        ) unless s3_env_files_in_sync

        Dotenv.load(S3_ENV_FILE)
      end

      def download_env_from_s3
        return if ENV["LOCAL_ENV"].to_i > 0
        S3Client.download_file(
          bucket: S3_BUCKET,
          key: UPLOADED_S3_ENV_FILE,
          destination: S3_ENV_FILE
        )
      end

      def upload_env_to_s3
        fail ".env file does not exist!" unless s3_env_file_exists?
        S3Client.upload_file(
          bucket: S3_BUCKET,
          key: UPLOADED_S3_ENV_FILE,
          file: S3_ENV_FILE
        )
      end

      private

      def s3_env_file_exists?
        File.exist?(S3_ENV_FILE)
      end

      def env_file_matches_shadow(file, shadow_file)
        sorted_env_vars(file) == sorted_env_vars(shadow_file)
      end

      def sorted_env_vars(file)
        File.read(file).scan(/(\w+)=/).uniq.flatten.sort
      end
    end
  end
end
