class DeerjikistsController < ApplicationController
  def show
    platform = params[:platform].to_s.strip
    code = params[:code].to_s.strip
    return render_bad_request('platform は必須です．') if platform.blank?
    return render_bad_request('code は必須です．') if code.blank?

    deerjikist = Deerjikist
                 .joins(:tag)
                 .includes(tag: :tag_name)
                 .find_by(platform:, code:)
    if deerjikist
      render json: DeerjikistRepr.base(deerjikist)
    else
      head :not_found
    end
  end

  def update
    return head :unauthorized unless current_user
    return head :forbidden unless current_user.gte_member?

    platform = params[:platform].to_s.strip
    code = params[:code].to_s.strip
    tag_id = params[:tag_id].to_i
    return render_bad_request('platform は必須です．') if platform.blank?
    return render_bad_request('code は必須です．') if code.blank?
    return render_bad_request('tag_id が不正です．') if tag_id <= 0

    deerjikist = Deerjikist.find_or_initialize_by(platform:, code:).tap do |d|
      d.tag_id = tag_id
      d.save!
    end

    render json: DeerjikistRepr.base(deerjikist)
  end

  def destroy
    return head :unauthorized unless current_user
    return head :forbidden unless current_user.gte_member?

    platform = params[:platform].to_s.strip
    code = params[:code].to_s.strip
    return render_bad_request('platform は必須です．') if platform.blank?
    return render_bad_request('code は必須です．') if code.blank?

    Deerjikist.find([platform, code]).destroy!

    head :no_content
  end
end
