class Admin::Library::BibsController < Admin::Library::Controller
  def index
    data = bibs
      .search_by_title(params[:title])
      .search_by_subtitle(params[:subtitle])
      .search_by_isbn(params[:isbn])
      .search_by_lccn(params[:lccn])

    render_success :ok, json: data.map { |b| bib_props(b) }
  end

  def show
    render_success :ok, json: bib_props(bib)
  end

  def create
    @bib = bibs.build(bib_params)

    if bib.save
      render_success :ok, json: bib
    else
      render_error :unprocessable_entity, errors: bib
    end
  end

  def update
    if bib.update(bib_params)
      render_success :ok
    else
      render_error :unprocessable_entity, errors: bib
    end
  end

  def destroy
    if bib.destroy
      render_success :ok
    else
      render_error :unprocessable_entity
    end
  end

  private
    def bibs
      current_school.library_bibs.includes(:publisher, :item_type, :bib_contributors)
    end

    def bib
      @bib ||= bibs.find_by(id: params[:id])
    end

    def item_type
      @item_type ||= current_school.library_item_types.find_by(id: params[:item_type_id])
    end

    def publisher
      @publisher ||= current_school.library_publishers.find_by(id: params[:publisher_id])
    end

    def set_associations
      {}.tap do |props|
        props[:item_type] = item_type if item_type
        props[:publisher] = publisher if publisher
      end
    end

    def bib_params
      params.permit(
        :title,
        :subtitle,
        :published_on,
        :isbn10,
        :isbn13,
        :lccn,
        :summary,
        :page_count,
        contributor_attributes: [:role, :id]
      ).merge(set_associations)
    end

    def bib_props(bib)
      {}.tap do |prop|
        prop[:id] = bib.id
        prop[:title] = bib.title
        prop[:subtitle] = bib.subtitle
        prop[:published_on] = bib.published_on
        prop[:isbn10] = bib.isbn10
        prop[:isbn13] = bib.isbn13
        prop[:lccn] = bib.lccn
        prop[:summary] = bib.summary
        prop[:page_count] = bib.page_count
        prop[:item_type_id] = bib.item_type_id
        return prop unless action_name.to_sym == :show

        prop[:publisher_id] = bib.publisher_id
        prop[:contributor_attributes] = bib.bib_contributors.map do |contributor|
          { id: contributor.contributor_id, role: contributor.role }
        end
      end
    end
end
