module Subscriptions
  class TicketProductRevenueConfigsController < Subscriptions::BaseController
    def index
      authorize TicketProductRevenueConfig

      @ticket_product_revenue_configs = Substwirp::RevenueConfig.get_configs_for_product_id(params[:id])
    end

    def edit
      authorize TicketProductRevenueConfig

      @config = Substwirp::RevenueConfig.get_by_id(params[:id])
    end

    def update
      authorize TicketProductRevenueConfig
      form_params = params[:substwirp_revenue_config]
      begin
        Substwirp::RevenueConfig.update(form_params[:id], form_params[:start_date], form_params[:rev_split_percent])
        flash[:success] = "Successfully updated revenue config"
      rescue StandardError => e
        flash[:error] = "Failed to update revenue config: #{e.message}"
      end
      redirect_back
    end

    def new
      authorize TicketProductRevenueConfig
      ticket_product_id = params[:ticket_product_id]
      @config = Substwirp::RevenueConfig.new
      @config.product_id = ticket_product_id
    end

    def create
      authorize TicketProductRevenueConfig
      form_params = params[:substwirp_revenue_config]
      begin
        Substwirp::RevenueConfig.create(form_params[:product_id], form_params[:start_date], form_params[:rev_split_percent])
        flash[:success] = "Successfully created revenue config"
      rescue StandardError => e
        flash[:error] = "Failed to create revenue config: #{e.message}"
      end
      redirect_back
    end

    def delete
      authorize TicketProductRevenueConfig
      begin
        Substwirp::RevenueConfig.delete(params[:ticket_product_revenue_config_id])
        flash[:success] = "Successfully deleted revenue config"
      rescue StandardError => e
        flash[:error] = "Failed to delete revenue config: #{e.message}"
      end
      redirect_back
    end
  end
end
