defmodule Web.Router do
  use Web, :router

  import Phoenix.LiveDashboard.Router
  import Oban.Web.Router
  import Web.UserAuth

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_live_flash
    plug :put_root_layout, html: {Web.Layouts, :root}
    plug :protect_from_forgery
    plug :put_secure_browser_headers
    plug :fetch_current_user
  end

  scope "/", Web do
    pipe_through [:browser, :redirect_if_user_is_authenticated]

    live_session :redirect_if_user_is_authenticated,
      on_mount: [{Web.UserAuth, :redirect_if_user_is_authenticated}] do
      live "/admin/users/register", UserRegistrationLive, :new
      live "/admin/users/log_in", UserLoginLive, :new
    end

    post "/admin/users/log_in", UserSessionController, :create
  end

  scope "/auth", Web do
    pipe_through [:browser, :require_authenticated_user]

    get "/mastodon", AuthController, :request
    get "/mastodon/callback", AuthController, :callback
  end

  scope "/admin", Web do
    pipe_through [:browser, :require_authenticated_user]

    live_dashboard "/dashboard"
    oban_dashboard "/oban"

    live_session :require_authenticated_user, on_mount: [{Web.UserAuth, :ensure_authenticated}] do
      live "/users/settings", UserSettingsLive, :edit

      live "/writing", AdminDashboardLive, :blog
      live "/microblog", AdminDashboardLive, :status

      live "/posts/new", AdminPostLive, :new
      live "/posts/:post_id", AdminPostLive, :edit

      live "/syndication", AdminSyndicationLive, :index
    end
  end

  scope "/", Web do
    pipe_through [:browser, :require_setup]

    get "/", PageController, :home

    delete "/admin/users/log_out", UserSessionController, :delete

    get "/blog", BlogController, :index
    get "/blog/:year/:month/:day/:slug", BlogController, :show
    get "/microblog", StatusController, :index
    get "/status/:status_id", StatusController, :show

    # live_session :current_user, on_mount: [{Web.UserAuth, :mount_current_user}] do
    # end
  end

  get "/atom.xml", Web.FeedController, :feed
end