class MessagesController < ApplicationController
  before_action :authenticate_user!

  def create
    if current_role == :client
      service_request = current_user.client_service_requests.where(id: params[:service_request_id])&.first
    end
    service_request = ServiceRequest.where(id: params[:service_request_id])&.first if current_role == :agent

    message = Message.create(
      message_params.merge(
        user: current_user,
        service_request_id: service_request.id
      )
    )

    if message.persisted?
      message.broadcast_append_to service_request,
                                  target: helpers.dom_id(service_request, :chat_messages),
                                  locals: { current_user: }
    else
      head :unprocessable_entity
    end
  end

  private

  def message_params
    params.require(:message).permit(
      :service_request_id, :text
    )
  end
end
