class Ecs::ImportCourseService < 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 Error, '文件不存在' if attachment.blank?

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

    created_count = 0
    EcCourse.bulk_insert(:name, :created_at, :updated_at) do |worker|
      excel.read_each do |course_name|
        next if ec_year.ec_courses.exists?(name: course_name)

        worker.add(name: course_name)
        created_count += 1
      end
    end

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