class Admin::Legacy::Service::OpportunitiesController < Admin::Legacy::Service::Controller
  def show
    render_success :ok, json: opportunity_props(opportunity)
  end

  def create
    opportunity = opportunities.build(opportunity_params)
    if opportunity.save
      render_success :ok, json: opportunity_props(opportunity)
    else
      render_error :unprocessable_entity, errors: opportunity
    end
  end

  def update
    if opportunity.update(opportunity_params)
      render_success :ok, json: opportunity_props(opportunity)
    else
      render_error :unprocessable_entity, errors: opportunity
    end
  end

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

  private
    def opportunities
      current_school.service_opportunities.includes(:student_logs, :family_logs)
    end

    def opportunity
      @opportunity ||= opportunities.find_by(id: params[:id])
    end

    def group
      @group || current_school.service_groups.find_by(id: params[:group_id])
    end

    def opportunity_params
      params.permit(:name, :description, :archived).merge(set_associations)
    end

    def set_associations
      { group: group }
    end

    def opportunity_props(opportunity)
      {
        id: opportunity.id,
        name: opportunity.name,
        description: opportunity.description,
        group_id: opportunity.group_id,
        archived: opportunity.archived,
        family_count: opportunity.family_logs.size,
        student_count: opportunity.student_logs.size
      }
    end
end
