defmodule Operately.Support.Factory.Accounts do
  alias Operately.Support.Factory.Utils

  def add_account(ctx, testid) do
    account =
      Operately.PeopleFixtures.account_fixture(%{
        full_name: Utils.testid_to_name(testid)
      })

    Map.put(ctx, testid, account)
  end

  def log_in_account(ctx, account_name) do
    account = Map.fetch!(ctx, account_name)
    conn = OperatelyWeb.TurboCase.log_in_account(ctx.conn, account)

    Map.put(ctx, :conn, conn)
  end

  def log_in_person(ctx, person_name) do
    person = Map.fetch!(ctx, person_name)

    login(ctx, person)
  end

  def log_in_contributor(ctx, contributor_name) do
    contributor = Map.fetch!(ctx, contributor_name)
    person = Operately.People.get_person(contributor.person_id)

    login(ctx, person)
  end

  defp login(ctx, person) do
    if ctx[:feature] == true do
      # we are running a feature test, log in via the UI
      Operately.Support.Features.UI.login_as(ctx, person)
    else
      # we are running an API test, log in via the API
      OperatelyWeb.TurboCase.log_in_account(ctx, person)
    end
  end
end
