defmodule BerrypodWeb.Shop.CustomPage do
  use BerrypodWeb, :live_view

  alias Berrypod.Pages

  @impl true
  def mount(_params, _session, socket) do
    {:ok, socket}
  end

  @impl true
  def handle_params(%{"slug" => slug}, _uri, socket) do
    page = Pages.get_page(slug)

    cond do
      is_nil(page) ->
        record_broken_url("/#{slug}")
        raise BerrypodWeb.NotFoundError

      page.type != "custom" ->
        raise BerrypodWeb.NotFoundError

      page.published != true and not socket.assigns.is_admin ->
        raise BerrypodWeb.NotFoundError

      true ->
        extra = Pages.load_block_data(page.blocks, socket.assigns)
        base = BerrypodWeb.Endpoint.url()

        socket =
          socket
          |> assign(:page_title, page.title)
          |> assign(:page, page)
          |> maybe_assign_meta(page, base)
          |> assign(extra)

        {:noreply, socket}
    end
  end

  @impl true
  def render(assigns) do
    ~H"""
    <BerrypodWeb.PageRenderer.render_page {assigns} />
    """
  end

  defp record_broken_url(path) do
    prior_hits = Berrypod.Analytics.count_pageviews_for_path(path)
    Berrypod.Redirects.record_broken_url(path, prior_hits)

    if prior_hits > 0 do
      Berrypod.Redirects.attempt_auto_resolve(path)
    end
  rescue
    _ -> :ok
  end

  defp maybe_assign_meta(socket, page, base) do
    socket
    |> assign(:og_url, base <> "/#{page.slug}")
    |> then(fn s ->
      if page.meta_description do
        assign(s, :page_description, page.meta_description)
      else
        s
      end
    end)
  end
end
