class Maglev::Editor::PagesController

def build_page_resource

def build_page_resource
  maglev_page_resources.build(page_params)
end

def create

def create
  @page = maglev_services.create_page.call(attributes: page_params)
  if @page.persisted?
    redirect_to editor_real_root_path(maglev_editing_route_context(page: @page)), status: :see_other
  else
    flash.now[:alert] = flash_t(:error)
    render :new, status: :unprocessable_content
  end
end

def destroy

def destroy
  @page.destroy!
  redirect_to editor_pages_path(**query_params, **maglev_editing_route_context(page: maglev_home_page)),
              notice: flash_t(:success), status: :see_other
end

def edit

def edit
  # we need to store the active tab in the flash
  # because we can't pass the anchor to the redirect
  @active_tab = flash[:active_tab]
end

def fetch_pages

def fetch_pages
  services.search_pages.call(
    q: params[:q],
    content_locale: content_locale,
    default_locale: default_content_locale,
    with_static_pages: false,
    index_first: true
  )
end

def index

def index
  @pages = fetch_pages
  @pagy, @pages = pagy(@pages, limit: per_page, page_param: 'offset') if pagination_enabled?
end

def new

def new
  @page = maglev_page_resources.build
end

def page_params

def page_params
  params.require(:page).permit(:title, :path,
                               :seo_title, :meta_description,
                               :og_title, :og_description, :og_image_url,
                               :visible, :lock_version)
end

def pagination_enabled?

def pagination_enabled?
  maglev_config.pagination?(:pages)
end

def per_page

def per_page
  maglev_config.per_page(:pages)
end

def query_params(from_list: false)

def query_params(from_list: false)
  base = { q: params[:q], from_list: params[:from_list] || from_list }
  (pagination_enabled? ? base.merge(offset: params[:offset]) : base).compact_blank
end

def set_page

def set_page
  @page = maglev_page_resources.find(params[:id])
end

def update

def update
  if @page.update(page_params)
    flash[:active_tab] = params[:active_tab]
    redirect_to edit_editor_page_path(@page, **query_params, **maglev_editing_route_context),
                notice: flash_t(:success), status: :see_other
  else
    flash.now[:alert] = flash_t(:error)
    render :edit, status: :unprocessable_content
  end
end