class Api::V1::Projects::Pulls::Journals::CreateService < ApplicationService 
  include ActiveModel::Model 

  attr_reader :project, :pull_request, :issue, :parent_id, :line_code, :note, :commit_id, :path, :type, :diff, :review_id, :user
  attr_accessor :journal

  validates :type, inclusion: {in: %w(comment problem), message: '请输入正确的Type'}

  def initialize(project, pull_request, params, user)
    @project = project 
    @pull_request = pull_request
    @issue = pull_request&.issue 
    @parent_id = params[:parent_id]
    @line_code = params[:line_code]
    @note = params[:note]
    @commit_id = params[:commit_id]
    @path = params[:path]
    @type = params[:type] || "comment"
    @diff = params[:diff]
    @review_id = params[:review_id]
    @user = user
  end

  def call 
    raise Error, errors.full_messages.join(", ") unless valid?
    check_review_is_exists if review_id.present?
    if type == 'problem'
      create_problem_journal
    else
      create_comment_journal
    end

    push_activity_2_blockchain("issue_comment_create", @journal) if Site.has_blockchain? && @project.use_blockchain

    journal
  end

  private 
  def create_comment_journal 
    @journal = pull_request.journals.create!(user_id: user&.id, notes: note, parent_id: parent_id, review_id: review_id, commit_id: commit_id, diff: diff, line_code: line_code, path: path)
  end

  def check_review_is_exists
    raise Error, '合并请求审查不存在！' unless @pull_request.reviews.exists?(review_id)
  end

  def create_problem_journal 
    @journal = pull_request.journals.create!(user_id: user&.id, notes: note, parent_id: parent_id, review_id: review_id, commit_id: commit_id, diff: diff, line_code: line_code, path: path, need_respond: true)
  end
end