class Competitions::CompetitionModulesController < Competitions::BaseController
  skip_before_action :require_login, only: [:index, :show]

  before_action :require_business, only: [:update]

  def index
    @modules = current_competition.unhidden_competition_modules.order(position: :asc)

    # 未登录、未获奖用户，不展示获奖证书栏目
    if !current_user.logged? || !current_competition.finished? || !current_competition.competition_prize_users.exists?(user: current_user)
      @modules = @modules.select { |mod| mod.name != '获奖证书' }
    end
  end

  def show
    @module = current_module
  end

  def update
    md = current_module.competition_module_md_content || current_module.build_competition_module_md_content
    md.name    = params[:md_name]
    md.content = params[:md_content]

    ActiveRecord::Base.transaction do
      md.save!

      attachment_ids = Array.wrap(params[:attachment_ids]).map(&:to_i)
      old_attachment_ids = md.attachments.pluck(:id)

      destroy_ids = old_attachment_ids - attachment_ids
      md.attachments.where(id: destroy_ids).delete_all
      Attachment.where(id: attachment_ids - old_attachment_ids).update_all(container: md)
    end

    render_ok
  end

  private

  def current_module
    @_current_module ||= current_competition.unhidden_competition_modules.find(params[:id])
  end
end
