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

  COURSE_MANAGER_COUNT_LIMIT = 2  # 课程管理员数量限制

  attr_reader :ec_course, :user_ids

  def initialize(ec_course, user_ids)
    @ec_course = ec_course
    @user_ids  = user_ids
  end

  def call
    users_count = User.where(id: user_ids).count
    raise Error, '用户不存在' if users_count != user_ids.size

    if ec_course.ec_course_users.exists?(user_id: user_ids)
      raise Error, '用户已经是该课程的管理员'
    end

    if ec_course.ec_course_users.count + user_ids.size > COURSE_MANAGER_COUNT_LIMIT
      raise Error, "课程管理员数量过多（最多#{COURSE_MANAGER_COUNT_LIMIT}）"
    end

    ActiveRecord::Base.transaction do
      user_ids.each do |user_id|
        ec_course.ec_course_users.create!(user_id: user_id)
      end
    end
  end
end