import Config

Envar.load(".env")
Envar.require_env_file(".env")

if System.get_env("PHX_SERVER") do
 config :api, ApiWeb.Endpoint, server: true
end

if config_env() == :prod do
 config :api, ApiWeb.Endpoint,
   check_origin: [Envar.get("CHECK_ORIGIN")]

 database_url = Envar.get("DATABASE_URL")
 pool_size = String.to_integer(System.get_env("POOL_SIZE") || "10")

 maybe_ipv6 = if System.get_env("ECTO_IPV6") in ~w(true 1), do: [:inet6], else: []

 config :api, Api.Repo,
   url: database_url,
   pool_size: pool_size,
   socket_options: maybe_ipv6

 # Configuración de Endpoint
 secret_key_base = Envar.get("SECRET_KEY_BASE")
 host = Envar.get("PHX_HOST")
 port = Envar.get("PHX_PORT")
 config :api, :dns_cluster_query, System.get_env("DNS_CLUSTER_QUERY")

 config :api, ApiWeb.Endpoint,
   url: [host: host, port: 80, scheme: Envar.get("SCHEME"), path: Envar.get("ROOT_PATH")],
   http: [
     ip: {127, 0, 0, 1},
     port: port || 4001
   ],
  secret_key_base: secret_key_base,
  server: true

end

case Envar.get("SMPT_TYPE") do
  "tls" ->
    config :api, Api.Mailer,
      adapter: Swoosh.Adapters.SMTP,
      relay: Envar.get("SMTP_RELAY"),
      port: String.to_integer(Envar.get("SMTP_PORT")) || Envar.get("SMTP_PORT"),
      username: Envar.get("SMTP_USER"),
      password: Envar.get("SMTP_PASS"),
      ssl: false,
      tls: :always,
      retries: 10,
      tls_options: [
        verify: :verify_peer,
        cacerts: :public_key.cacerts_get(),
        server_name_indication: String.to_charlist(Envar.get("SERVER_NAME_INDICATION") || ~c"#{Envar.get("SERVER_NAME_INDICATION")}"),
        depth: 99
      ]

  "ssl" ->
    config :api, Api.Mailer,
      adapter: Swoosh.Adapters.SMTP,
      relay: Envar.get("SMTP_RELAY"),
      username: Envar.get("SMTP_USER"),
      password: Envar.get("SMTP_PASS"),
      auth: :always,
      ssl: true,
      port: String.to_integer(Envar.get("SMTP_PORT")) || Envar.get("SMTP_PORT"),
      retries: 10,
      sockopts: [
        versions: [:"tlsv1.2"],
        verify: :verify_peer,
        cacerts: :public_key.cacerts_get(),
        depth: 3,
        customize_hostname_check: [
          match_fun: :public_key.pkix_verify_hostname_match_fun(:https)
        ],
        server_name_indication: Envar.get("SERVER_NAME_INDICATION")
      ]
    _ -> nil
end
