class Cooperative::LaboratorySubjectsController < Cooperative::BaseController
  before_action :check_subject_ownership!, only: [:edit, :update]

  helper_method :current_laboratory_subject

  def index
    laboratory_subjects = Admins::LaboratorySubjectQuery.call(current_laboratory, params)

    includes_tables = { subject: [:repertoire, :subject_level_system, user: {user_extension: :school}] }
    @laboratory_subjects = paginate(laboratory_subjects.includes(includes_tables))
  end

  def edit
    @laboratory_subject = current_laboratory_subject
  end

  def update
    current_laboratory_subject.subject.update!(update_params)
  end

  def destroy
    return render_js_error('不能删除自建实践课程', type: :notify) if current_laboratory_subject.ownership?
    current_laboratory_subject.destroy!

    render_delete_success
  end

  def homepage
    current_laboratory_subject.update!(homepage: true)
    render_ok
  end

  def cancel_homepage
    current_laboratory_subject.update!(homepage: false)
    render_ok
  end

  private

  def current_laboratory_subject
    @_current_laboratory_subject ||= current_laboratory.laboratory_subjects.find(params[:id])
  end

  def check_subject_ownership!
    return if current_laboratory_subject.ownership?

    render_forbidden
  end

  def update_params
    params.require(:laboratory_subject).permit(:repertoire_id, :subject_level_system_id)
  end
end