defmodule Tarakan.MarketFixtures do
  @moduledoc """
  Test helpers for the bounty marketplace.
  """

  alias Tarakan.Accounts.Account
  alias Tarakan.Accounts.Scope
  alias Tarakan.Credits
  alias Tarakan.Market
  alias Tarakan.Repo

  @doc "An account fixture promoted to active standing (bounties require it)."
  def active_account_fixture(attrs \\ %{}) do
    account = Tarakan.AccountsFixtures.account_fixture(attrs)

    account
    |> Account.authorization_changeset(%{
      state: "active",
      platform_role: account.platform_role,
      trust_tier: account.trust_tier
    })
    |> Repo.update!()
  end

  @doc "Tops up an account's credit balance and returns the fresh account row."
  def fund_credits(%Account{} = account, amount) do
    {:ok, _entry} = Credits.credit(account, :receive_bounty, nil, amount)
    Repo.get!(Account, account.id)
  end

  def valid_bounty_attributes(repository, overrides \\ %{}) do
    Enum.into(overrides, %{
      "target_type" => "repository",
      "target_ref" => "#{repository.owner}/#{repository.name}",
      "title" => "Fix the session auth bypass",
      "description" =>
        "Reproduce the authorization bypass in the session handler and ship a reviewed fix.",
      "funding" => "credits",
      "credit_amount" => 500
    })
  end

  @doc "Creates a credits-funded bounty on the given listed repository."
  def credits_bounty_fixture(%Scope{} = scope, repository, overrides \\ %{}) do
    {:ok, bounty} =
      Market.create_bounty(scope, valid_bounty_attributes(repository, overrides))

    bounty
  end

  @doc "Creates a fiat bounty on the given listed repository (Stripe stubbed)."
  def fiat_bounty_fixture(%Scope{} = scope, repository, overrides \\ %{}) do
    attrs =
      repository
      |> valid_bounty_attributes(overrides)
      |> Map.merge(%{"funding" => "fiat", "amount_cents" => 25_000})
      |> Map.delete("credit_amount")

    {:ok, bounty, checkout_url} = Market.create_bounty(scope, attrs)
    {bounty, checkout_url}
  end

  @doc "Legacy-prose submission attrs accepted by Work.submit_task/3 in tests."
  def submission_attributes do
    %{
      "provenance" => "human",
      "summary" => "Traced the bypass and patched the guard clause.",
      "evidence" => "Reproduced locally against the pinned commit; patch and test attached."
    }
  end
end
