defmodule CMSWeb.Router do
  use CMSWeb, :router

  import CMSWeb.AdminAuth
  import CMSWeb.Globals

  alias CMSWeb.AdminAuth
  alias CMSWeb.Globals

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

  pipeline :supports_admin_action do
    plug :mount_admin
  end

  pipeline :requires_admin do
    plug :mount_admin
    plug :require_admin
  end

  live_session :default, on_mount: [AdminAuth, Globals] do
    scope "/", CMSWeb do
      pipe_through :browser
      pipe_through :supports_admin_action

      get "/", PageController, :home

      get "/writing", PostController, :index
      get "/writing/:post_id", PostController, :show

      live "/sign-in", AdminLoginLive
      post "/admin/session/create", AdminSessionController, :create
      get "/admin/session/destroy", AdminSessionController, :destroy
    end

    scope "/admin", CMSWeb do
      pipe_through :browser
      pipe_through :requires_admin

      live "/", AdminLive

      live "/writing/new", PostLive, :new
      live "/writing/:post_id", PostLive, :edit

      live "/microblog/new", StatusLive, :new
      live "/microblog/:status_id", StatusLive, :edit
    end
  end

  # Enable LiveDashboard in development
  if Application.compile_env(:cms, :dev_routes) do
    # If you want to use the LiveDashboard in production, you should put
    # it behind authentication and allow only admins to access it.
    # If your application does not have an admins-only section yet,
    # you can use Plug.BasicAuth to set up some basic authentication
    # as long as you are also using SSL (which you should anyway).
    import Phoenix.LiveDashboard.Router

    scope "/dev" do
      pipe_through :browser

      live_dashboard "/dashboard", metrics: CMSWeb.Telemetry
    end
  end
end