module RevenueReporting
  class ReportsController < RevenueReporting::BaseController

    def index
      authorize Report

      # index screen is also the new report form
      @report = Report.new
      authorize @report

      @reports = Report.scoped
      @reports = @reports.where(params[:report]) if params[:report].present?
      @reports = @reports.page(params[:page]).per_page(params[:per_page])
      @reports = @reports.all
    end

    def create
      @report = Report.new report_params
      authorize @report

      if @report.save
        flash[:success] = "Success"
      else
        flash[:danger] = @report.errors.full_messages.to_sentence
      end
      redirect_to revenue_reporting_reports_path
    end

    def tax_withholding_rates
      @report = Report.new(
        :report_type => :tax_withholding_rates,
        :start_date => Time.now.utc.strftime("%F")
      )
      authorize @report

      if @report.save
        flash[:success] = "Success"
      else
        flash[:danger] = @report.errors.full_messages.to_sentence
      end
      redirect_to revenue_reporting_reports_path
    end

    protected

    def report_params
      params.require(:revenue_reporting_report).permit(:id, :report_type, :start_date, :state, :payload)
    end
  end
end
