class EmpenhoParaFechamentoPcasp < ApplicationRecord
	validates_presence_of :orcamento_id, :empenho_id, :valor, :tipo

	belongs_to :orcamento
	belongs_to :empenho

	enum tipo: {
		credito_suplementar: 0,
		credito_especial: 1,
		credito_extraordinario: 2,
		credito_de_reducao: 3,
		saldo_inicial: 9
	}

	scope :empenhos, -> { where("empenho_id is not null and liquidacao_id is null") }
	scope :liquidacoes, -> { where("liquidacao_id is not null and pagamento_id is null") }
	scope :pagamentos, -> { where("pagamento_id is not null") }

	def saldo
		if self.pagamento_id.present?
			self.valor
		elsif self.liquidacao_id.present? && self.pagamento_id.nil?
			self.valor - EmpenhoParaFechamentoPcasp.where(liquidacao_id: self.liquidacao_id, tipo: self.tipo).pagamentos.sum(:valor)
		else
			self.valor - EmpenhoParaFechamentoPcasp.where(empenho_id: self.empenho_id, tipo: self.tipo).liquidacoes.sum(:valor)
		end
	end

end
