class Ecs::ImportStudentService < ApplicationService
  Error = Class.new(StandardError)

  attr_reader :ec_year, :attachment

  def initialize(ec_year, attachment_id)
    @ec_year    = ec_year
    @attachment = Attachment.find_by(id: attachment_id)
  end

  def call
    raise_import_error('文件不存在') if attachment.blank?

    path = attachment.diskfile
    excel = Ecs::ImportStudentExcel.new(path)

    success_count = 0
    EcYearStudent.bulk_insert(:student_id, :name, :created_at, :updated_at) do |worker|
      excel.read_each do |student_id, name|
        success_count += 1

        student = ec_year.ec_year_students.find_by(student_id: student_id)
        if student.present?
          student.update!(name: name)
          next
        end

        worker.add(student_id: student_id, name: name)
      end
    end

    success_count
  rescue BaseImportExcel::Error => ex
    raise Error, ex.message
  end
end