defmodule CentralcloudStaff.WazuhMcpController do
  @moduledoc """
  MCP (Model Context Protocol) endpoint for the Wazuh security analyst agent.

  Accepts JSON-RPC 2.0 POST requests at /api/mcp/wazuh and dispatches to
  CentralcloudCore.WazuhMcp.

  Auth: Bearer token via WAZUH_MCP_API_KEY env var (in-cluster agents only).
  """

  use Phoenix.Controller, formats: [:json]

  alias CentralcloudCore.WazuhMcp

  # Handle batched and single JSON-RPC requests
  def call(conn, _params) do
    with :ok <- check_auth(conn),
         {:ok, body, conn} <- Plug.Conn.read_body(conn),
         {:ok, rpc} <- Jason.decode(body) do
      response =
        case rpc do
          requests when is_list(requests) -> Enum.map(requests, &WazuhMcp.handle/1)
          request when is_map(request) -> WazuhMcp.handle(request)
        end

      conn
      |> put_resp_content_type("application/json")
      |> send_resp(200, Jason.encode!(response))
    else
      {:error, :unauthorized} ->
        conn
        |> put_resp_content_type("application/json")
        |> send_resp(401, Jason.encode!(%{error: "unauthorized"}))

      {:error, :invalid_json} ->
        conn
        |> put_resp_content_type("application/json")
        |> send_resp(400, Jason.encode!(%{error: "invalid JSON"}))

      {:error, reason} ->
        conn
        |> put_resp_content_type("application/json")
        |> send_resp(500, Jason.encode!(%{error: inspect(reason)}))
    end
  end

  defp check_auth(conn) do
    expected = Application.get_env(:centralcloud_staff, :wazuh_mcp_api_key, "")

    case Plug.Conn.get_req_header(conn, "authorization") do
      ["Bearer " <> token] when expected != "" and token == expected -> :ok
      _ when expected == "" -> :ok
      _ -> {:error, :unauthorized}
    end
  end
end
