class TheatreCommentsController < ApplicationController
  def index
    limit = params[:limit].to_i
    limit = 20 if limit <= 0

    no_gt = params[:no_gt].to_i
    no_gt = 0 if no_gt < 0

    comments = TheatreComment
               .where(theatre_id: params[:theatre_id])
               .where('no > ?', no_gt)
               .order(no: :desc)
               .limit(limit)

    render json: comments.map {
      _1.as_json(include: { user: { only: [:id, :name] } })
          .merge(content: _1.discarded? ? nil : _1.content, deleted: _1.discarded?)
    }
  end

  def create
    return head :unauthorized unless current_user

    content = params[:content]
    return render_unprocessable_entity('本文は必須です．', field: :content) if content.blank?

    theatre = Theatre.find_by(id: params[:theatre_id])
    return head :not_found unless theatre

    comment = nil
    theatre.with_lock do
      no = theatre.next_comment_no
      comment = TheatreComment.create!(theatre:, no:, user: current_user, content:)
      theatre.update!(next_comment_no: no + 1)
    end

    render json: comment, status: :created
  end

  def destroy
    return head :unauthorized unless current_user

    theatre_id = params[:theatre_id].to_i
    no = params[:id].to_i

    comment = TheatreComment.find_by(theatre_id:, no:)
    return head :not_found unless comment
    return head :forbidden unless comment.user == current_user

    comment.discard!

    head :no_content
  end
end
