class School::Legacy::Service::OpportunitiesController < ApplicationController
  def index

    data = opportunities
      .by_group(params[:group_id])
      .not_archived(params[:include_archived])
      .or(opportunities.where(id: params[:id]))
      .order(:name)
      .map { |o| opportunity_props(o) }
    render_success :ok, json: data
  end

  private
    def opportunities
      current_school.service_opportunities.includes(:group) do
        includes(:family_logs, :student_logs) if params[:include_counts]&.to_bool
      end
    end

    def opportunity_props(opportunity)
      {}.tap do |prop|
        prop[:id] = opportunity.id
        prop[:name] = opportunity.name
        prop[:description] = opportunity.description
        prop[:group_id] = opportunity.group_id
        prop[:group_name] = opportunity.decorate.group_name
        prop[:archived] = opportunity.archived
        return prop unless params[:include_counts]&.to_bool

        prop[:family_count] = opportunity.family_logs.size
        prop[:student_count] = opportunity.student_logs.size
      end
    end
end
