import Config

import Bitwise
import String, only: [to_integer: 1]
import System

guild_id =
  case fetch_env!("GUILD_ID") do
    "global" -> :global
    id -> String.to_integer(id)
  end

config :clipper_bot,
  guild_id: guild_id,
  app_id: fetch_env!("APP_ID") |> to_integer(),
  # Guild intent
  intents: 1 <<< 0,
  bot_token: fetch_env!("BOT_TOKEN")

config :clipper_bot,
  clip_dir: fetch_env!("CLIP_DIR"),
  clip_dir_max_size: fetch_env!("CLIP_DIR_MAX_SIZE") |> String.to_integer()

segment_dir_max_size =
  case get_env("SEGMENT_DIR_MAX_SIZE") do
    nil -> 10 ** 9
    max_size -> to_integer(max_size)
  end

config :clipper_bot, ClipperBot.Mailer, %{
  mail_from: get_env("MAIL_FROM"),
  mail_to: get_env("MAIL_TO")
}

config :clipper_bot,
  segment_dir: get_env("SEGMENT_DIR", tmp_dir() |> Path.join("segment_dir")),
  segment_dir_max_size: segment_dir_max_size

config :clipper_bot, Web.Endpoint,
  url: [
    host: get_env("HOST", "localhost"),
    port: 8080
  ],
  http: [
    port: get_env("PORT", "8080"),
    ip: :any
  ]

if config_env() == :prod do
  config :clipper_bot,
    segment_dir: fetch_env!("SEGMENT_DIR"),
    segment_dir_max_size: segment_dir_max_size

  config :clipper_bot, Db.Repo,
    database: get_env("DATABASE", "db_repo"),
    username: get_env("DB_USERNAME", "postgres"),
    password: get_env("DB_PASSWORD", "dev_postgres_pw"),
    hostname: "localhost",
    log: false

  config :logger, :default_handler,
    config: [
      type: :file,
      file: fetch_env!("LOG_FILE") |> String.to_charlist(),
      max_no_bytes: 5_000_000,
      max_no_files: 20
    ]

  config :clipper_bot, Web.Endpoint,
    url: [
      host: fetch_env!("HOST")
    ],
    http: [
      port: get_env("PORT", "80"),
      ip: :any
    ]

  if get_env("SSL_KEY_FILE", "") != "" do
    config :clipper_bot, Web.Endpoint,
      https: [
        port: 443,
        ip: :any,
        otp_app: :web,
        # in priv dir if not absolute
        keyfile: fetch_env!("SSL_KEY_FILE"),
        certfile: fetch_env!("SSL_CERT_FILE")
      ]
  end

  config :clipper_bot,
    admin_username: "admin",
    admin_password: fetch_env!("ADMIN_PASSWORD")
end
