module Contabilidade
	class EstornosDePagamentoController < ApplicationController
		include ControllerConcern
		before_action :authenticate_usuario!
		before_action :autoriza_usuario!
		before_action :set_pagamento, only: [:new, :create]
		before_action :set_estorno_de_pagamento, only: [:show, :destroy]

		def show
			@pagamento = @estorno_de_pagamento.pagamento
		end
		# GET /contabilidade/estornos_de_pagamento/new
		def new
			if @pagamento.estornado
				redirect_to @pagamento, alert: 'Pagamento já foi estornado.'
			else
				@estorno_de_pagamento = @pagamento.build_estorno_de_pagamento
			end
		end

		# POST /contabilidade/estornos_de_pagamento
		def create
			@estorno_de_pagamento = @pagamento.build_estorno_de_pagamento(estorno_de_pagamento_params)
			@estorno_de_pagamento.usuario_id = current_usuario.try(:id)
			if @estorno_de_pagamento.save
				redirect_to @pagamento, notice: 'Pagamento estornado com sucesso'
			else
				flash[:alert] = "Pagamento não pode ser estornado, verifique os dados do pagamento."
				render :new
			end
		end

		def destroy
			mensagem = apaga_e_retorna_mensagem(@estorno_de_pagamento)
			redirect_to @estorno_de_pagamento.pagamento, mensagem
		end


		private
		def set_pagamento
			@pagamento = Pagamento.find( params[:pagamento_id] )
		end

		def set_estorno_de_pagamento
			@estorno_de_pagamento = Contabilidade::EstornoDePagamento.find( params[:id] )
		end


		# Permite apenas os parâmetros específicos
		def estorno_de_pagamento_params
			params.require(:contabilidade_estorno_de_pagamento).permit(:data_do_estorno, :justificativa)
		end
	end
end
