class Admin::Legacy::Facility::LocationsController < Admin::Legacy::Facility::Controller
  def index
    render_success :ok, json: locations.map { |l| location_props(l) }
  end

  def show
    location.migrate_photo
    render_success :ok, json: location_props(location)
  end

  def create
    location = locations.build(location_params)

    if location.save
      render_success :ok, json: location_props(location)
    else
      render_error :unprocessable_entity, errors: location
    end
  end

  def update
    if location.update(location_params)
      render_success :ok, json: location_props(location)
    else
      render_error :unprocessable_entity, errors: location
    end
  end

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

  private
    def locations
      current_school.facility_locations
    end

    def location
      @location ||= locations.find_by(id: params[:id])
    end

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

    def location_props(location)
      {
        id: location.id,
        name: location.name,
        description: location.description,
        address_1: location.address_1,
        address_2: location.address_2,
        city: location.city,
        state: location.state,
        zip: location.zip,
        notes: location.notes,
        photo_url: location.photo.attachment&.service_url,
        photo_filename: location.photo.attachment&.filename
      }
    end
end
