defmodule TarakanWeb.Endpoint do
  use Phoenix.Endpoint, otp_app: :tarakan

  # The session will be stored in the cookie and signed,
  # this means its contents can be read but not tampered with.
  # Set :encryption_salt if you would also like to encrypt it.
  @session_options [
    store: :cookie,
    key: "_tarakan_key",
    signing_salt: "z2pFa4vB",
    encryption_salt: "PS6crKxQ",
    same_site: "Lax",
    secure: Application.compile_env(:tarakan, :secure_cookies, true)
  ]

  socket "/live", Phoenix.LiveView.Socket,
    websocket: [connect_info: [:peer_data, :x_headers, session: @session_options]],
    longpoll: [connect_info: [:peer_data, :x_headers, session: @session_options]]

  # Force SSL in prod with the X-Forwarded-Proto scheme rewrite gated on
  # trusted proxies. Phoenix would insert Plug.SSL ahead of every plug below
  # when :force_ssl is configured, leaving its rewrite_on honoring the header
  # from any peer, so prod sets :trusted_ssl instead and both plugs run here,
  # first and in order.
  if trusted_ssl = Application.compile_env(:tarakan, [__MODULE__, :trusted_ssl]) do
    plug TarakanWeb.Plugs.ForwardedProto
    plug Plug.SSL, trusted_ssl
  end

  # Serve at "/" the static files from "priv/static" directory.
  #
  # When code reloading is disabled (e.g., in production),
  # the `gzip` option is enabled to serve compressed
  # static files generated by running `phx.digest`.
  plug Plug.Static,
    at: "/",
    from: :tarakan,
    gzip: not code_reloading?,
    only: TarakanWeb.static_paths(),
    raise_on_missing_only: code_reloading?

  # Code reloading can be explicitly enabled under the
  # :code_reloader configuration of your endpoint.
  if code_reloading? do
    socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
    plug Phoenix.LiveReloader
    plug Phoenix.CodeReloader
    plug Phoenix.Ecto.CheckRepoStatus, otp_app: :tarakan
  end

  plug Phoenix.LiveDashboard.RequestLogger,
    param_key: "request_logger",
    cookie_key: "request_logger"

  plug Plug.RequestId
  plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]

  # Rewrite remote_ip from X-Forwarded-For only when the peer is a configured
  # trusted proxy (see :trusted_proxies). Must run before rate limiters / git.
  plug TarakanWeb.Plugs.ClientIp

  # Git smart HTTP must run before Plug.Parsers: RPC bodies stream to a git
  # subprocess and would otherwise be buffered and rejected at the parser's
  # size cap. Non-git requests pass straight through.
  plug TarakanWeb.GitHTTP

  plug Plug.Parsers,
    parsers: [:urlencoded, :multipart, :json],
    pass: ["*/*"],
    length: 2_500_000,
    body_reader: {TarakanWeb.Endpoint, :read_body, []},
    json_decoder: Phoenix.json_library()

  # Plug.Parsers body_reader wrapper: caches the raw request body in
  # conn.assigns[:raw_body] so the Stripe webhook controller can verify the
  # Stripe-Signature HMAC against the exact payload bytes.
  @doc false
  def read_body(conn, opts) do
    case Plug.Conn.read_body(conn, opts) do
      {:ok, body, conn} ->
        {:ok, body, Plug.Conn.assign(conn, :raw_body, body)}

      {:more, chunk, conn} ->
        {:more, chunk,
         Plug.Conn.assign(conn, :raw_body, (conn.assigns[:raw_body] || "") <> chunk)}

      {:error, reason} ->
        {:error, reason}
    end
  end

  plug Plug.MethodOverride
  plug Plug.Head
  plug Plug.Session, @session_options
  plug TarakanWeb.Router
end
