defmodule Moba.Admin.Items do
  @moduledoc """
  Admin functions for managing Items, mostly generated by Torch package.
  """

  alias Moba.{Repo, Game}
  alias Game.Schema.Item
  alias Game.Query.ItemQuery

  import Ecto.Query, warn: false
  import Torch.Helpers, only: [sort: 1, paginate: 4]
  import Filtrex.Type.Config

  @pagination [page_size: 50]
  @pagination_distance 5

  def paginate(params \\ %{}) do
    params =
      params
      |> Map.put_new("sort_direction", "desc")
      |> Map.put_new("sort_field", "inserted_at")

    {:ok, sort_direction} = Map.fetch(params, "sort_direction")
    {:ok, sort_field} = Map.fetch(params, "sort_field")

    with {:ok, filter} <- Filtrex.parse_params(filter_config(:items), params["item"] || %{}),
         %Scrivener.Page{} = page <- do_paginate(filter, params) do
      {:ok,
       %{
         items: page.entries,
         page_number: page.page_number,
         page_size: page.page_size,
         total_pages: page.total_pages,
         total_entries: page.total_entries,
         distance: @pagination_distance,
         sort_field: sort_field,
         sort_direction: sort_direction
       }}
    else
      {:error, error} -> {:error, error}
      error -> {:error, error}
    end
  end

  def list do
    Repo.all(Item)
  end

  def get!(id), do: Repo.get!(Item, id)

  def create(attrs \\ %{}) do
    %Item{}
    |> Item.changeset(attrs)
    |> Repo.insert()
  end

  def update(%Item{} = item, attrs) do
    item
    |> Item.changeset(attrs)
    |> Repo.update()
  end

  def delete(%Item{} = item) do
    Repo.delete(item)
  end

  def change(%Item{} = item) do
    Item.changeset(item, %{})
  end

  defp do_paginate(filter, params) do
    ItemQuery.canon()
    |> Filtrex.query(filter)
    |> order_by(^sort(params))
    |> paginate(Repo, params, @pagination)
  end

  defp filter_config(:items) do
    defconfig do
      boolean(:enabled)
      text(:name)
      text(:description)
      text(:code)
      text(:rarity)
      number(:mp_cost)
      number(:cooldown)
      boolean(:active)
      boolean(:passive)
    end
  end
end
