# typed: false
# frozen_string_literal: true

OP_VAULT_SECRETS = {}
OP_INFRA_SECRETS = {}

def fetch_vault_secret(label:, default: "")
  if productionish?
    OP_VAULT_SECRETS.delete(label) || raise("Secret `#{label}` not found in 1Password")
  else
    ENV.fetch(label, default.is_a?(Pathname) ? default.read : default)
  end
end

def fetch_infra_secret(label:, default: "")
  if productionish?
    OP_INFRA_SECRETS.delete(label) || raise("Secret `#{label}` not found in 1Password")
  else
    ENV.fetch(label, default.is_a?(Pathname) ? default.read : default)
  end
end

def op_load_vault_into_env(vault:, tag: nil)
  include_sudo = !Rails.env.local? ? "sudo -E " : ""
  include_tag = tag ? " --tags #{tag} " : ""
  %x(#{include_sudo}op item list --vault #{vault}#{include_tag}--format json | #{include_sudo}op item get - --reveal --format=json).tap do
    raise "Failed to fetch value `#{vault}` for `#{tag}` from 1Password" unless $CHILD_STATUS.success?
  end
end

def load_vault_secret(field)
  OP_VAULT_SECRETS[field["label"]] = field["value"].gsub("\\n", "\n")
end

def load_infra_secret(field)
  OP_INFRA_SECRETS[field["label"]] = field["value"].gsub("\\n", "\n")
end

def productionish?
  Rails.env.production? || Rails.env.staging?
end

def print_user_api_errors?
  (Rails.env.development? || Rails.env.staging?) || ENV.fetch("DEBUG", false)
end

def plug_shortname
  plug_name.downcase
end

def plug_name
  plug_module[4..] # 4= "Plug".length
end

def plug_module
  Rails.application.class.module_parent.name
end

def plug_url
  if Rails.env.production?
    "#{plug_shortname}.plugs.yetto.app"
  elsif Rails.env.staging?
    "#{plug_shortname}.plugs.yetto.dev"
  elsif Rails.env.development?
    "#{%x(hostname).chomp.downcase}-plug-#{plug_shortname}.ngrok.io"
  elsif Rails.env.test?
    "#{plug_shortname}.plugs.yetto.test"
  end
end

module Hephaestus
  YETTO_EMAIL_DOMAIN = if Rails.env.production?
    "yetto.email"
  elsif Rails.env.staging?
    "yetto.dev"
  elsif Rails.env.development?
    "yetto-dev.email"
  elsif Rails.env.test?
    "yetto.test"
  end

  PROTOCOL = Rails.env.development? ? "http://" : "https://"
  YETTO_URL = if Rails.env.production?
    "web.yetto.app"
  elsif Rails.env.staging?
    "web.yetto.dev"
  elsif Rails.env.development?
    "localhost:3000"
  elsif Rails.env.test?
    "web.yetto.test"
  end

  # Every plug has secrets; to reduce the amount of API calls to 1Password,
  # we can grab one document that contains all the secrets we need
  if productionish?
    res = JSON.parse(op_load_vault_into_env(vault: "Plug-#{plug_name}", tag: ENV["RAILS_ENV"]))
    ["Common", "Unique", "Yetto"].each do |section_label|
      res["fields"].select { |f| f["section"] && f["section"]["label"] }.each do |field|
        next unless field["section"]["label"] == section_label

        load_vault_secret(field)
      end
    end

    res = JSON.parse(op_load_vault_into_env(vault: "Infra", tag: ENV["RAILS_ENV"]))
    ["Common"].each do |section_label|
      res["fields"].select { |f| f["section"] && f["section"]["label"] }.each do |field|
        next unless field["section"]["label"] == section_label

        load_infra_secret(field)
      end
    end
  end

  YETTO_API_URL = "#{YETTO_URL}/api"
  YETTO_REDIRECT_URL = productionish? ? "#{PROTOCOL}#{YETTO_URL}" : "#{PROTOCOL}127.0.0.1:3000"

  YETTO_PLUG_PEM = fetch_vault_secret(
    label: "YETTO_PLUG_PEM",
    default: Rails.root.join("test/fixtures/files/fake_pem_file/fake.pem"),
  )

  YETTO_SIGNING_SECRET = fetch_vault_secret(
    label: "YETTO_SIGNING_SECRET",
    # this is a fake 32-bit secret
    default: "caae20f6dcb2b745003abe043f2d9b56",
  )

  YETTO_PLUG_ID = fetch_vault_secret(
    label: "YETTO_PLUG_ID",
    default: "plug-id",
  )
end