class Admin::Legacy::Facility::RoomsController < Admin::Legacy::Facility::Controller
  def index
    data = rooms.by_buildings(params[:building_ids])
    render_success :ok, json: data.map { |r| room_props(r) }
  end

  def show
    room.migrate_photo
    render_success :ok, json: room_props(room)
  end

  def create
    room = rooms.build(room_params)

    if room.save
      render_success :ok, json: room_props(room)
    else
      render_error :unprocessable_entity, errors: room
    end
  end

  def update
    if room.update(room_params)
      render_success :ok, json: room_props(room)
    else
      render_error :unprocessable_entity, errors: room
    end
  end

  def destroy
    if room.destroy
      render_success :ok
    else
      render_error :unprocessable_entity, errors: room
    end
  end

  private
    def rooms
      current_school.facility_rooms.includes(:building)
    end

    def room
      @room ||= rooms.find_by(id: params[:id])
    end

    def room_params
      params.permit(:name, :description, :number, :capacity, :notes, :photo).merge(associations)
    end

    def associations
      {}.tap do |prop|
        prop[:building] = building if params.key?(:building_id)
        prop[:owner] = owner if params.key?(:owner_id)
        prop[:alert] = params[:alert]&.to_bool
      end
    end

    def owner
      @owner ||= current_school.users.find_by(id: params[:owner_id])
    end

    def building
      @building ||= current_school.facility_buildings.find_by(id: params[:building_id])
    end

    def room_props(room)
      {
        id: room.id,
        name: room.name,
        description: room.description,
        building_id: room.building_id,
        building_name: room.decorate.building_name,
        number: room.number,
        capacity: room.capacity,
        owner_id: room.owner_id,
        alert: room.alert?,
        notes: room.notes,
        photo_url: room.photo.attachment&.service_url,
        photo_filename: room.photo.attachment&.filename
      }
    end
end
