defmodule Mv.Membership.Member.Changes.SetDefaultMembershipFeeType do
  @moduledoc """
  Ash change that automatically assigns the default membership fee type to new members
  if no membership_fee_type_id is explicitly provided.

  This change reads the default_membership_fee_type_id from global settings and
  assigns it to the member if membership_fee_type_id is nil.
  """
  use Ash.Resource.Change

  @spec change(Ash.Changeset.t(), keyword(), Ash.Resource.Change.context()) :: Ash.Changeset.t()
  def change(changeset, _opts, _context) do
    # Only set default if membership_fee_type_id is not already set
    current_type_id = Ash.Changeset.get_attribute(changeset, :membership_fee_type_id)

    if is_nil(current_type_id) do
      apply_default_membership_fee_type(changeset)
    else
      changeset
    end
  end

  defp apply_default_membership_fee_type(changeset) do
    case Mv.Membership.get_settings() do
      {:ok, settings} ->
        if settings.default_membership_fee_type_id do
          Ash.Changeset.force_change_attribute(
            changeset,
            :membership_fee_type_id,
            settings.default_membership_fee_type_id
          )
        else
          changeset
        end

      {:error, _error} ->
        # If settings can't be loaded, continue without default
        # This prevents member creation from failing if settings are misconfigured
        changeset
    end
  end
end
