import Config

app_role =
  case System.get_env("APP_ROLE", "web") do
    "web" -> :web
    "worker" -> :worker
    "combined" -> :combined
    "migrate" -> :migrate
    other -> raise "APP_ROLE must be web, worker, combined, or migrate; got #{inspect(other)}"
  end

rate_limit_policies =
  case System.get_env("RATE_LIMIT_POLICIES_JSON") do
    value when value in [nil, ""] ->
      %{}

    json ->
      case Jason.decode(json) do
        {:ok, policies} when is_map(policies) ->
          invalid_action =
            Enum.find_value(policies, fn
              {action, %{"limit" => limit, "window_seconds" => window}}
              when is_binary(action) and action != "" and is_integer(limit) and limit > 0 and
                     is_integer(window) and window > 0 ->
                nil

              {action, _policy} ->
                if is_binary(action) and action != "", do: action, else: "<invalid action>"
            end)

          if invalid_action do
            raise """
            RATE_LIMIT_POLICIES_JSON policy #{inspect(invalid_action)} must contain positive \
            integer limit and window_seconds values.
            """
          end

          policies

        {:ok, _other} ->
          raise "RATE_LIMIT_POLICIES_JSON must be a JSON object."

        {:error, _reason} ->
          raise "RATE_LIMIT_POLICIES_JSON must contain valid JSON."
      end
  end

config :who_need_help,
  app_role: app_role,
  codex_session_id: System.get_env("CODEX_SESSION_ID", "not-configured"),
  map_tile_url:
    System.get_env(
      "MAP_TILE_URL",
      Application.fetch_env!(:who_need_help, :map_tile_url)
    ),
  rate_limit_policies: rate_limit_policies

optional_positive_integer = fn name ->
  case System.get_env(name) do
    value when value in [nil, ""] ->
      nil

    value ->
      case Integer.parse(value) do
        {integer, ""} when integer > 0 ->
          integer

        _other ->
          raise "#{name} must be a positive integer when configured."
      end
  end
end

required_positive_integer = fn name ->
  case optional_positive_integer.(name) do
    nil -> raise "#{name} is required when the HTTP push boundary is enabled."
    value -> value
  end
end

positive_integer_with_default = fn name, default ->
  optional_positive_integer.(name) || default
end

if config_env() == :prod do
  config :who_need_help, Oban,
    queues: [
      maintenance: positive_integer_with_default.("OBAN_MAINTENANCE_CONCURRENCY", 2),
      push: positive_integer_with_default.("OBAN_PUSH_CONCURRENCY", 1)
    ]
end

required_non_negative_integer = fn name ->
  case System.get_env(name) do
    value when value in [nil, ""] ->
      raise "#{name} is required when the HTTP push boundary is enabled."

    value ->
      case Integer.parse(value) do
        {integer, ""} when integer >= 0 ->
          integer

        _other ->
          raise "#{name} must be a non-negative integer."
      end
  end
end

allow_insecure_external_http =
  case System.get_env("ALLOW_INSECURE_EXTERNAL_HTTP", "false") do
    "true" -> true
    "false" -> false
    other -> raise "ALLOW_INSECURE_EXTERNAL_HTTP must be true or false; got #{inspect(other)}"
  end

oauth_endpoint = fn name, default ->
  value =
    case System.get_env(name) do
      configured when configured in [nil, ""] -> default
      configured -> configured
    end

  case URI.parse(value) do
    %URI{scheme: scheme, host: host}
    when is_binary(host) and host != "" and
           (scheme == "https" or (scheme == "http" and allow_insecure_external_http)) ->
      value

    _other ->
      raise """
      #{name} must be an absolute HTTPS URL. Plain HTTP is allowed only in the \
      isolated external-boundary drill with ALLOW_INSECURE_EXTERNAL_HTTP=true.
      """
  end
end

oauth_http_options = fn prefix ->
  [retry: false]
  |> then(fn options ->
    case optional_positive_integer.("#{prefix}_OAUTH_HTTP_RECEIVE_TIMEOUT_MS") do
      nil -> options
      timeout -> Keyword.put(options, :receive_timeout, timeout)
    end
  end)
  |> then(fn options ->
    case optional_positive_integer.("#{prefix}_OAUTH_HTTP_CONNECT_TIMEOUT_MS") do
      nil -> options
      timeout -> Keyword.put(options, :connect_options, timeout: timeout)
    end
  end)
end

github_oauth =
  case {
    System.get_env("GITHUB_OAUTH_CLIENT_ID"),
    System.get_env("GITHUB_OAUTH_CLIENT_SECRET")
  } do
    {client_id, client_secret}
    when is_binary(client_id) and client_id != "" and is_binary(client_secret) and
           client_secret != "" ->
      %{
        github: [
          client_id: client_id,
          client_secret: client_secret,
          base_url: oauth_endpoint.("GITHUB_OAUTH_BASE_URL", "https://api.github.com"),
          authorize_url:
            oauth_endpoint.(
              "GITHUB_OAUTH_AUTHORIZE_URL",
              "https://github.com/login/oauth/authorize"
            ),
          token_url:
            oauth_endpoint.(
              "GITHUB_OAUTH_TOKEN_URL",
              "https://github.com/login/oauth/access_token"
            ),
          user_url: oauth_endpoint.("GITHUB_OAUTH_USER_URL", "https://api.github.com/user"),
          http_adapter: {Assent.HTTPAdapter.Req, oauth_http_options.("GITHUB")}
        ]
      }

    {client_id, client_secret} when client_id in [nil, ""] and client_secret in [nil, ""] ->
      %{}

    _partial_configuration ->
      raise """
      GITHUB_OAUTH_CLIENT_ID and GITHUB_OAUTH_CLIENT_SECRET must either both be set or both be empty.
      """
  end

config :who_need_help, :social_oauth, github_oauth

google_auth =
  case {
    System.get_env("GOOGLE_OAUTH_CLIENT_ID"),
    System.get_env("GOOGLE_OAUTH_CLIENT_SECRET")
  } do
    {client_id, client_secret}
    when is_binary(client_id) and client_id != "" and is_binary(client_secret) and
           client_secret != "" ->
      [
        client_id: client_id,
        client_secret: client_secret,
        base_url: oauth_endpoint.("GOOGLE_OAUTH_BASE_URL", "https://accounts.google.com/"),
        authorization_params: [scope: "email profile"],
        http_adapter: {Assent.HTTPAdapter.Req, oauth_http_options.("GOOGLE")}
      ]

    {client_id, client_secret} when client_id in [nil, ""] and client_secret in [nil, ""] ->
      []

    _partial_configuration ->
      raise """
      GOOGLE_OAUTH_CLIENT_ID and GOOGLE_OAUTH_CLIENT_SECRET must either both be set or both be empty.
      """
  end

config :who_need_help, :google_auth, google_auth

push_configuration =
  case {
    System.get_env("PUSH_HTTP_ENDPOINT"),
    System.get_env("PUSH_HTTP_BEARER_TOKEN")
  } do
    {endpoint, bearer_token}
    when is_binary(endpoint) and endpoint != "" and is_binary(bearer_token) and
           bearer_token != "" ->
      case URI.parse(endpoint) do
        %URI{scheme: scheme, host: host}
        when is_binary(host) and host != "" and
               (scheme == "https" or (scheme == "http" and allow_insecure_external_http)) ->
          :ok

        _other ->
          raise """
          PUSH_HTTP_ENDPOINT must be an absolute HTTPS URL. Plain HTTP is allowed only \
          in the isolated external-boundary drill with ALLOW_INSECURE_EXTERNAL_HTTP=true.
          """
      end

      [
        adapter: WhoNeedHelp.Push.HTTPAdapter,
        endpoint: endpoint,
        bearer_token: bearer_token,
        max_attempts: required_positive_integer.("PUSH_HTTP_MAX_ATTEMPTS"),
        receive_timeout: required_positive_integer.("PUSH_HTTP_RECEIVE_TIMEOUT_MS"),
        connect_timeout: required_positive_integer.("PUSH_HTTP_CONNECT_TIMEOUT_MS"),
        retry_delay_ms: required_non_negative_integer.("PUSH_HTTP_RETRY_DELAY_MS")
      ]

    {endpoint, bearer_token} when endpoint in [nil, ""] and bearer_token in [nil, ""] ->
      []

    _partial_configuration ->
      raise """
      PUSH_HTTP_ENDPOINT and PUSH_HTTP_BEARER_TOKEN must either both be set or both be empty.
      """
  end

config :who_need_help,
  push_product_enabled: push_configuration != [],
  push_adapter:
    Keyword.get(
      push_configuration,
      :adapter,
      WhoNeedHelp.Push.DisabledAdapter
    ),
  push_delivery_options: Keyword.delete(push_configuration, :adapter)

if config_env() == :prod and app_role in [:web, :worker, :combined] do
  metrics_token =
    System.get_env("METRICS_TOKEN") ||
      raise """
      environment variable METRICS_TOKEN is missing for the web, worker, or combined role.
      Generate an independent random value and store it in the deployment secret.
      """

  if metrics_token == "" do
    raise "METRICS_TOKEN must not be empty for the web, worker, or combined role."
  end

  config :who_need_help, :metrics_token, metrics_token
end

case System.get_env("DNS_CLUSTER_QUERY") do
  query when query in [nil, "", "ignore"] ->
    config :who_need_help, :dns_cluster_query, :ignore

  query ->
    config :who_need_help, :dns_cluster_query, query
end

# config/runtime.exs is executed for all environments, including
# during releases. It is executed after compilation and before the
# system starts, so it is typically used to load production configuration
# and secrets from environment variables or elsewhere. Do not define
# any compile-time configuration in here, as it won't be applied.
# The block below contains prod specific runtime configuration.

# ## Using releases
#
# If you use `mix release`, you need to explicitly enable the server
# by passing the PHX_SERVER=true when you start it:
#
#     PHX_SERVER=true bin/who_need_help start
#
# Alternatively, you can use `mix phx.gen.release` to generate a `bin/server`
# script that automatically sets the env var above.
if System.get_env("PHX_SERVER") do
  config :who_need_help, WhoNeedHelpWeb.Endpoint, server: true
end

config :who_need_help, WhoNeedHelpWeb.Endpoint,
  http: [port: String.to_integer(System.get_env("PORT", "4000"))]

if config_env() == :dev do
  # Reload browser tabs when matching files change.
  config :who_need_help, WhoNeedHelpWeb.Endpoint,
    live_reload: [
      web_console_logger: true,
      patterns: [
        # Static assets, except user uploads
        ~r"priv/static/(?!uploads/).*\.(js|css|png|jpeg|jpg|gif|svg)$",
        # Gettext translations
        ~r"priv/gettext/.*\.po$",
        # Router, Controllers, LiveViews and LiveComponents
        ~r"lib/who_need_help_web/router\.ex$",
        ~r"lib/who_need_help_web/(controllers|live|components)/.*\.(ex|heex)$"
      ]
    ]
end

if config_env() == :prod do
  database_url =
    System.get_env("DATABASE_URL") ||
      raise """
      environment variable DATABASE_URL is missing.
      For example: ecto://USER:PASS@HOST/DATABASE
      """

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

  database_socket_dir =
    case System.get_env("DATABASE_SOCKET_DIR") do
      value when value in [nil, ""] ->
        nil

      "/" <> _rest = value ->
        value

      _other ->
        raise "DATABASE_SOCKET_DIR must be an absolute path when configured."
    end

  repo_options =
    [
      url: database_url,
      pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"),
      socket_options: maybe_ipv6
    ]
    |> then(fn options ->
      if database_socket_dir do
        Keyword.put(options, :socket_dir, database_socket_dir)
      else
        options
      end
    end)

  config :who_need_help, WhoNeedHelp.Repo, repo_options

  # The secret key base is used to sign/encrypt cookies and other secrets.
  # A default value is used in config/dev.exs and config/test.exs but you
  # want to use a different value for prod and you most likely don't want
  # to check this value into version control, so we use an environment
  # variable instead.
  secret_key_base =
    System.get_env("SECRET_KEY_BASE") ||
      raise """
      environment variable SECRET_KEY_BASE is missing.
      You can generate one by calling: mix phx.gen.secret
      """

  handover_secret =
    System.get_env("HANDOVER_SECRET") ||
      raise """
      environment variable HANDOVER_SECRET is missing.
      Generate an independent random value for deterministic handover codes.
      """

  host = System.get_env("PHX_HOST") || "example.com"
  scheme = System.get_env("PHX_SCHEME", "https")

  unless scheme in ["http", "https"] do
    raise "PHX_SCHEME must be http or https; got #{inspect(scheme)}"
  end

  default_url_port = if scheme == "https", do: "443", else: "80"
  url_port = String.to_integer(System.get_env("PHX_URL_PORT", default_url_port))

  email_delivery_provider = System.get_env("EMAIL_DELIVERY_PROVIDER", "smtp")

  mailer_config =
    case email_delivery_provider do
      "smtp" ->
        smtp_auth =
          case System.get_env("SMTP_AUTH", "never") do
            "always" ->
              :always

            "never" ->
              :never

            "if_available" ->
              :if_available

            other ->
              raise "SMTP_AUTH must be always, never, or if_available; got #{inspect(other)}"
          end

        smtp_tls =
          case System.get_env("SMTP_TLS", "never") do
            "always" ->
              :always

            "never" ->
              :never

            "if_available" ->
              :if_available

            other ->
              raise "SMTP_TLS must be always, never, or if_available; got #{inspect(other)}"
          end

        smtp_ssl =
          case System.get_env("SMTP_SSL", "false") do
            value when value in ["true", "1"] -> true
            value when value in ["false", "0"] -> false
            other -> raise "SMTP_SSL must be true, false, 1, or 0; got #{inspect(other)}"
          end

        smtp_username = System.get_env("SMTP_USERNAME")
        smtp_password = System.get_env("SMTP_PASSWORD")
        smtp_username_set? = is_binary(smtp_username) and smtp_username != ""
        smtp_password_set? = is_binary(smtp_password) and smtp_password != ""

        if smtp_username_set? != smtp_password_set? do
          raise "SMTP_USERNAME and SMTP_PASSWORD must either both be set or both be empty."
        end

        if smtp_auth == :always and not (smtp_username_set? and smtp_password_set?) do
          raise "SMTP_USERNAME and SMTP_PASSWORD are required when SMTP_AUTH is always."
        end

        if smtp_ssl and smtp_tls != :never do
          raise "SMTP_TLS must be never when SMTP_SSL enables an implicit TLS connection."
        end

        [
          adapter: Swoosh.Adapters.SMTP,
          relay: System.get_env("SMTP_RELAY", "mailpit"),
          port: String.to_integer(System.get_env("SMTP_PORT", "1025")),
          auth: smtp_auth,
          tls: smtp_tls,
          ssl: smtp_ssl
        ]
        |> then(fn config ->
          case smtp_username do
            value when is_binary(value) and value != "" -> Keyword.put(config, :username, value)
            _ -> config
          end
        end)
        |> then(fn config ->
          case smtp_password do
            value when is_binary(value) and value != "" -> Keyword.put(config, :password, value)
            _ -> config
          end
        end)

      "unisender_go" ->
        api_key =
          System.get_env("UNISENDER_GO_API_KEY") ||
            raise "UNISENDER_GO_API_KEY is required when EMAIL_DELIVERY_PROVIDER=unisender_go."

        if api_key == "" do
          raise "UNISENDER_GO_API_KEY is required when EMAIL_DELIVERY_PROVIDER=unisender_go."
        end

        base_url =
          System.get_env(
            "UNISENDER_GO_BASE_URL",
            "https://goapi.unisender.ru/ru/transactional/api/v1"
          )
          |> String.trim_trailing("/")

        uri = URI.parse(base_url)

        unless uri.scheme == "https" and is_binary(uri.host) and uri.host != "" and
                 is_binary(uri.path) and uri.path != "" and is_nil(uri.userinfo) and
                 is_nil(uri.query) and is_nil(uri.fragment) do
          raise "UNISENDER_GO_BASE_URL must be an HTTPS origin and path without credentials, query, or fragment."
        end

        skip_unsubscribe =
          case System.get_env("UNISENDER_GO_SKIP_UNSUBSCRIBE", "false") do
            "true" ->
              true

            "false" ->
              false

            other ->
              raise "UNISENDER_GO_SKIP_UNSUBSCRIBE must be true or false; got #{inspect(other)}"
          end

        client_options =
          []
          |> then(fn options ->
            case optional_positive_integer.("EMAIL_HTTP_CONNECT_TIMEOUT_MS") do
              nil -> options
              timeout -> Keyword.put(options, :connect_options, timeout: timeout)
            end
          end)
          |> then(fn options ->
            case optional_positive_integer.("EMAIL_HTTP_RECEIVE_TIMEOUT_MS") do
              nil -> options
              timeout -> Keyword.put(options, :receive_timeout, timeout)
            end
          end)

        [
          adapter: WhoNeedHelp.Email.UnisenderGoAdapter,
          api_key: api_key,
          base_url: base_url,
          skip_unsubscribe: skip_unsubscribe,
          client_options: client_options
        ]

      other ->
        raise "EMAIL_DELIVERY_PROVIDER must be smtp or unisender_go; got #{inspect(other)}"
    end

  config :who_need_help, :handover_secret, handover_secret

  config :who_need_help, :mailer_from,
    name: System.get_env("EMAIL_FROM_NAME", "Who Need Help"),
    address: System.get_env("EMAIL_FROM_ADDRESS", "contact@example.com")

  support_inbox_address =
    case System.get_env("SUPPORT_INBOX_ADDRESS") do
      value when value in [nil, ""] -> nil
      value -> value
    end

  if support_inbox_address &&
       not Regex.match?(~r/^[^@,;\s]+@[^@,;\s]+$/, support_inbox_address) do
    raise "SUPPORT_INBOX_ADDRESS must be a single email address without spaces."
  end

  config :who_need_help, :support_inbox_address, support_inbox_address

  config :who_need_help, WhoNeedHelp.Mailer, mailer_config

  config :who_need_help, WhoNeedHelpWeb.Endpoint,
    url: [host: host, port: url_port, scheme: scheme],
    http: [
      # Enable IPv6 and bind on all interfaces.
      # Set it to  {0, 0, 0, 0, 0, 0, 0, 1} for local network only access.
      # See the documentation on https://bandit.hexdocs.pm/Bandit.html#t:options/0
      # for details about using IPv6 vs IPv4 and loopback vs public addresses.
      ip: {0, 0, 0, 0, 0, 0, 0, 0}
    ],
    secret_key_base: secret_key_base

  # ## SSL Support
  #
  # To get SSL working, you will need to add the `https` key
  # to your endpoint configuration:
  #
  #     config :who_need_help, WhoNeedHelpWeb.Endpoint,
  #       https: [
  #         ...,
  #         port: 443,
  #         cipher_suite: :strong,
  #         keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
  #         certfile: System.get_env("SOME_APP_SSL_CERT_PATH")
  #       ]
  #
  # The `cipher_suite` is set to `:strong` to support only the
  # latest and more secure SSL ciphers. This means old browsers
  # and clients may not be supported. You can set it to
  # `:compatible` for wider support.
  #
  # `:keyfile` and `:certfile` expect an absolute path to the key
  # and cert in disk or a relative path inside priv, for example
  # "priv/ssl/server.key". For all supported SSL configuration
  # options, see https://plug.hexdocs.pm/Plug.SSL.html#configure/1
  #
  # We also recommend setting `force_ssl` in your config/prod.exs,
  # ensuring no data is ever sent via http, always redirecting to https:
  #
  #     config :who_need_help, WhoNeedHelpWeb.Endpoint,
  #       force_ssl: [hsts: true]
  #
  # Check `Plug.SSL` for all available options in `force_ssl`.

  # ## Configuring the mailer
  #
  # In production you need to configure the mailer to use a different adapter.
  # Here is an example configuration for Mailgun:
  #
  #     config :who_need_help, WhoNeedHelp.Mailer,
  #       adapter: Swoosh.Adapters.Mailgun,
  #       api_key: System.get_env("MAILGUN_API_KEY"),
  #       domain: System.get_env("MAILGUN_DOMAIN")
  #
  # Most non-SMTP adapters require an API client. Swoosh supports Req, Hackney,
  # and Finch out-of-the-box. This configuration is typically done at
  # compile-time in your config/prod.exs:
  #
  #     config :swoosh, :api_client, Swoosh.ApiClient.Req
  #
  # See https://swoosh.hexdocs.pm/Swoosh.html#module-installation for details.
end
