class Support::Sites::StoragesController < Support::Sites::Controller
  include CacheHelper

  def index
    render_success :ok, json: schools.map { |s| storage_props(s) }.compact
  end

  private
    def schools
      School.by_active(true).decorate
    end

    def number_to_human_size(size)
      ActionController::Base.helpers.number_to_human_size(size)
    end

    def areas
      [
        :school_documents,
        :school_photos,
        :class_documents,
        :class_photos,
        :student_profile_documents,
        :employee_profile_documents,
        :user_documents
      ]
    end

    def storage_props(school)
      school_storage = load_cache("school/#{school.id}/file_storage")
      return if school_storage.nil?

      # Get all storage area sizes in bytes to calculate the total
      # Format all byte sizes to human readable sizes after calculations
      total = 0
      storage_sizes = areas.map do |area|
        file_size = school_storage[area]
        total += file_size
        [area, { readable: number_to_human_size(file_size), bytes: file_size }]
      end.to_h

      {
        id: school.id,
        readable: number_to_human_size(total),
        bytes: total,
        updated_at: school_storage[:updated_at]
      }.merge(storage_sizes)
    end
end
