defmodule ToweropsWeb.Plugs.MobileAuth do
  @moduledoc """
  Plug for authenticating mobile app requests using bearer tokens.

  Expects an Authorization header with format: "Bearer <token>"

  On success, assigns :current_user and :current_mobile_session to the conn.
  On failure, returns 401 Unauthorized.
  """

  import Phoenix.Controller, only: [json: 2]
  import Plug.Conn

  alias Towerops.Accounts
  alias Towerops.MobileSessions

  def init(opts), do: opts

  def call(conn, _opts) do
    with {:ok, token} <- extract_token(conn),
         {:ok, session} <- validate_session(token),
         {:ok, user} <- get_user(session.user_id) do
      # Touch the session to update last_used_at
      _ = Task.start(fn -> MobileSessions.touch_session(session) end)

      conn
      |> assign(:current_user, user)
      |> assign(:current_mobile_session, session)
    else
      {:error, reason} ->
        conn
        |> put_status(:unauthorized)
        |> json(%{error: error_message(reason)})
        |> halt()
    end
  end

  defp extract_token(conn) do
    case get_req_header(conn, "authorization") do
      ["Bearer " <> token] -> {:ok, token}
      _ -> {:error, :missing_token}
    end
  end

  defp validate_session(token) do
    case MobileSessions.get_session_by_token(token) do
      nil -> {:error, :invalid_token}
      session -> {:ok, session}
    end
  end

  defp get_user(user_id) do
    case Accounts.get_user(user_id) do
      nil -> {:error, :user_not_found}
      user -> {:ok, user}
    end
  end

  defp error_message(:missing_token), do: "Authorization header is missing or invalid"
  defp error_message(:invalid_token), do: "Invalid or expired authentication token"
  defp error_message(:user_not_found), do: "User not found"
end
