class Api::Pm::Issues::BatchDeleteService < ApplicationService
  include ActiveModel::Model

  attr_reader :project, :issues, :current_user

  validates :project, :issues, :current_user, presence: true

  def initialize(project, issues, current_user = nil)
    @project = project 
    @issues = issues.includes(:assigners)
    @current_user = current_user
  end

  def call 
    raise Error, errors.full_messages.join(", ") unless valid? 
    try_lock("Api::V1::Issues::DeleteService:#{project.id}") # 开始写数据，加锁

    delete_issues

    project.incre_project_issue_cache_delete_count(@issues.size)

    if Site.has_notice_menu? && !project.id.zero?
      @issues.each do |issue|
        SendTemplateMessageJob.perform_later('IssueDeleted', current_user.id, @issue&.subject, @issue.assigners.pluck(:id), @issue.author_id) 
      end
    end

    unlock("Api::V1::Issues::DeleteService:#{project.id}")

    return true
  end

  private

  def delete_issues
    raise Error, "批量删除疑修失败！" unless @issues.destroy_all
  end
end