class Admin::Legacy::Student::Students::OriginsController < Admin::Legacy::Student::Controller
  def show
    render_success :ok, json: origins.map { |o| origin_props(o) }
  end

  def update
    student.assign_attributes(origin_params)

    if student.save
      render_success :ok, object: :ethnicity
    else
      render_error :unprocessable_entity, errors: student
    end
  end

  private
    def student
      @student ||= current_school.students.find_by(id: params[:student_id])
    end

    def origins
      student.origins.by_origin(params[:origin])
    end

    def ethnic_descriptors
      EdFi::Wisconsin::DescriptorService
        .call(current_school_year.id, descriptor: :ancestryethnicorigindescriptors)
        .map { |d| [d['id'], d['codeValue'].split('-').first] }
        .to_h
    end

    def origin_params
      params.permit(:ethnicity, :origin, origin_descriptors: [])
    end

    def origin_props(origin)
      {
        origin: origin.origin,
        descriptor: origin.descriptor,
        type: ethnic_descriptors[origin.descriptor] || :tribal
      }
    end
end
