defmodule Mv.Secrets do
  @moduledoc """
  Secret provider for AshAuthentication.

  ## Purpose
  Provides runtime configuration secrets for Ash Authentication strategies,
  particularly for OIDC (Rauthy) authentication.

  ## Configuration Source
  Secrets are read from the `:rauthy` key in the application configuration,
  which is typically set in `config/runtime.exs` from environment variables:
  - `OIDC_CLIENT_ID`
  - `OIDC_CLIENT_SECRET`
  - `OIDC_BASE_URL`
  - `OIDC_REDIRECT_URI`

  ## Usage
  This module is automatically called by AshAuthentication when resolving
  secrets for the User resource's OIDC strategy.
  """
  use AshAuthentication.Secret

  def secret_for(
        [:authentication, :strategies, :rauthy, :client_id],
        Mv.Accounts.User,
        _opts,
        _meth
      ) do
    get_config(:client_id)
  end

  def secret_for(
        [:authentication, :strategies, :rauthy, :redirect_uri],
        Mv.Accounts.User,
        _opts,
        _meth
      ) do
    get_config(:redirect_uri)
  end

  def secret_for(
        [:authentication, :strategies, :rauthy, :client_secret],
        Mv.Accounts.User,
        _opts,
        _meth
      ) do
    get_config(:client_secret)
  end

  def secret_for(
        [:authentication, :strategies, :rauthy, :base_url],
        Mv.Accounts.User,
        _opts,
        _meth
      ) do
    get_config(:base_url)
  end

  defp get_config(key) do
    :mv
    |> Application.fetch_env!(:rauthy)
    |> Keyword.fetch!(key)
    |> then(&{:ok, &1})
  end
end
