defmodule ApiWeb.Router do
  use ApiWeb, :router

  pipeline :api do
    plug :accepts, ["json"]
  end

  pipeline :gatekeeper do
    plug AssignShape

    plug Auth.AuthenticateUser
    plug Auth.AuthorizeShapeAccess
  end

  pipeline :proxy do
    plug AssignShape

    plug Auth.VerifyToken
  end

  scope "/" do
    pipe_through :api

    # The gatekeeper endpoint at `POST /gatekeeper/:table` authenticates the user,
    # authorizes the shape access, generates a shape-scoped auth token and returns
    # this along with other config that an Electric client can use to stream the
    # shape directly from Electric.
    scope "/gatekeeper" do
      pipe_through :gatekeeper

      post "/:table", Electric.Phoenix.Plug,
        authenticator: &Authenticator.authentication_headers/2
    end

    # The proxy endpoint at `GET /proxy/v1/shape` proxies the request to an
    # upstream Electric service.
    #
    # Access to this endpoint is protected by the `:proxy` pipeline, which verifies
    # a shape signed token, generated by the gatekeeper endpoint above.
    scope "/proxy", ApiWeb do
      pipe_through :proxy

      get "/v1/shape", ProxyController, :show
    end
  end
end
