defmodule WhoNeedHelpWeb.MobileTrackingController do
  use WhoNeedHelpWeb, :controller

  alias WhoNeedHelp.Accounts.Scope
  alias WhoNeedHelp.{Help, Tracking}

  def update(conn, %{"assignment_id" => assignment_id} = params) do
    with %Scope{user: user} = scope when not is_nil(user) <- conn.assigns.current_scope,
         {:ok, assignment} <- Help.get_assignment_for_participant(scope, assignment_id),
         {:ok, _position} <- Tracking.update_position(scope, assignment, params) do
      send_resp(conn, :no_content, "")
    else
      nil -> send_resp(conn, :unauthorized, "")
      %Scope{user: nil} -> send_resp(conn, :unauthorized, "")
      {:error, :not_found} -> send_resp(conn, :not_found, "")
      {:error, :forbidden} -> send_resp(conn, :forbidden, "")
      {:error, :blocked} -> send_resp(conn, :forbidden, "")
      {:error, :assignment_inactive} -> send_resp(conn, :conflict, "")
      {:error, :tracking_not_active} -> send_resp(conn, :conflict, "")
      {:error, :rate_limited} -> send_resp(conn, :too_many_requests, "")
      {:error, %Ecto.Changeset{}} -> send_resp(conn, :unprocessable_entity, "")
      {:error, _reason} -> send_resp(conn, :unprocessable_entity, "")
    end
  end

  def stop(conn, %{"assignment_id" => assignment_id}) do
    with %Scope{user: user} = scope when not is_nil(user) <- conn.assigns.current_scope,
         {:ok, assignment} <- Help.get_assignment_for_participant(scope, assignment_id),
         {:ok, _result} <- Tracking.stop_session(scope, assignment) do
      send_resp(conn, :no_content, "")
    else
      nil -> send_resp(conn, :unauthorized, "")
      %Scope{user: nil} -> send_resp(conn, :unauthorized, "")
      {:error, :not_found} -> send_resp(conn, :not_found, "")
      {:error, :forbidden} -> send_resp(conn, :forbidden, "")
      {:error, _reason} -> send_resp(conn, :unprocessable_entity, "")
    end
  end
end
