class Admin::AccountsController < Admin::ApplicationController
  before_action :set_account, only: [:show, :edit, :update]

  def index
    @accounts = filtered_accounts.order_by_name.paginate(page: params[:page])
  end

  def new
    @account = build_account
  end

  def create
    @account = build_account(account_params)
    if @account.save
      redirect_to account_auths_path({ account_id: @account.id }), notice: t(".notice")
    else
      render :new
    end
  end

  def show
    @videos = filtered_account_videos.order(created_at: :desc, project_id: :desc).paginate(page: params[:page])
  end

  def edit
  end

  def update
    if @account.update(account_params)
      redirect_to admin_accounts_path, notice: t(".notice")
    else
      render :edit
    end
  end

  private

  def set_account
    @account = find_account
  end

  def find_account
    authorize accounts.find_by(slug: params[:id])
  end

  def accounts
    policy_scope(Account)
  end

  def build_account(params = {})
    authorize accounts.new(params)
  end

  def account_params
    params.require(:account).permit(:name, :plan_uid)
  end

  def filtered_accounts
    if params[:query].present?
      accounts.search(params[:query])
    else
      accounts
    end
  end

  def filtered_account_videos
    if params[:query].present?
      @account.videos.search(params[:query])
    else
      @account.videos
    end
  end
end
