module Agent
  class ServiceCentersController < ApplicationController
    before_action :authenticate_user!
    before_action -> { authenticate_role!(:agent, :admin) }

    def update
      return head :unauthorized unless current_user.can_close_service_center

      service_center = ServiceCenter.first
      service_center.update(service_center_params)

      if service_center.open_previously_changed? ||
         service_center.client_message_previously_changed? ||
         service_center.client_message_enabled_previously_changed?
        broadcast_updates
        head :ok
      else
        flash[:info] = t("shared.messages.saved")
        render turbo_stream: update_flash_messages_turbo_stream
      end
    end

    private

    def broadcast_updates
      ServiceCenter.first.broadcast_replace_to [:agent, ServiceCenter.first],
                                               target: helpers.dom_id(ServiceCenter.first, :edit),
                                               partial: "layouts/service_center_open_toggle",
                                               locals: { current_user: }

      ServiceCenter.first.broadcast_replace_to [:client, ServiceCenter.first],
                                               target: :opening_hours_label,
                                               partial: "layouts/opening_hours_label",
                                               locals: { current_user: }

      ServiceCenter.first.broadcast_replace_to [:client, ServiceCenter.first],
                                               target: :new_service_request,
                                               partial: "client/home/new_service_request",
                                               locals: { current_user: }

      ServiceCenter.first.broadcast_update_to [:client, ServiceCenter.first],
                                              target: helpers.dom_id(ServiceCenter.first),
                                              partial: "client/home/service_center_client_message",
                                              locals: { current_user: }
    end

    def service_center_params
      params.require(:service_center).permit(:open, :client_message, :client_message_enabled)
    end
  end
end
