class Admin::Legacy::Facility::BuildingsController < Admin::Legacy::Facility::Controller
  def index
    data = buildings.by_locations(params[:location_ids])
    render_success :ok, json: data.map { |b| building_props(b) }
  end

  def show
    building.migrate_photo
    render_success :ok, json: building_props(building)
  end

  def create
    building = buildings.build(building_params)

    if building.save
      render_success :ok, json: building_props(building)
    else
      render_error :unprocessable_entity, errors: building
    end
  end

  def update
    if building.update(building_params)
      render_success :ok, json: building_props(building)
    else
      render_error :unprocessable_entity, errors: building
    end
  end

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

  private
    def buildings
      current_school.facility_buildings
    end

    def building
      @building ||= buildings.find_by(id: params[:id])
    end

    def building_params
      params.permit(
        :name,
        :description,
        :address_1,
        :address_2,
        :city,
        :state,
        :zip,
        :notes,
        :photo
      ).merge(associations)
    end

    def associations
      {}.tap do |prop|
        prop[:location] = location if params.key?(:location_id)
        prop[:owner] = owner if params.key?(:owner_id)
      end
    end

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

    def location
      @location ||= current_school.facility_locations.find_by(id: params[:location_id])
    end

    def building_props(building)
      {
        id: building.id,
        location_id: building.location_id,
        name: building.name,
        description: building.description,
        address_1: building.address_1,
        address_2: building.address_2,
        city: building.city,
        state: building.state,
        zip: building.zip,
        owner_id: building.owner_id,
        notes: building.notes,
        alert: building.alert?,
        photo_url: building.photo.attachment&.service_url,
        photo_filename: building.photo.attachment&.filename
      }
    end
end
