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

  attr_reader :project, :pull_request, :journal, :note, :commit_id, :state, :user
  attr_accessor :updated_journal 

  validates :state, inclusion: {in: %w(opened resolved disabled)}

  def initialize(project, pull_request, journal, params, user)
    @project = project
    @pull_request = pull_request
    @journal = journal
    @note = params[:note]
    @commit_id = params[:commit_id]
    @state = params[:state] 
    @user = user
  end

  def call 
    raise Error, errors.full_messages.join(", ") unless valid?

    update_journal 

    updated_journal
  end

  private 
  def update_journal 
    journal.attributes = {notes: note, commit_id: commit_id, state: state}
    if state == 'resolved'
      journal.resolve_at = Time.now 
      journal.resolveer_id = user.id
    end
    return Error, '保存评论失败！' unless journal.save

    @updated_journal = journal.reload
  end
end