module Bits
  class TypesController < Bits::BaseController
    before_action :set_type, only: [:show, :edit, :update]
    before_action :set_enums, only: [:new, :edit]

    def index
      authorize Type

      begin
        @types = Type.all
      rescue StandardError
        @types = []
        flash.now[:error] = "Error loading product types"
      end
    end

    def new
      @type = Type.new
      authorize @type
    end

    def create
      @type = build_type type_params
      authorize @type

      if @type.save
        flash[:success] = "Success created new Bits Type [#{@type.display_name}]"
        redirect_to bits_types_path
      else
        flash[:error] = @type.errors.full_messages.to_sentence
        render :new
      end
    end

    def edit
    end

    def update
      @type = build_type type_params

      if @type.save
        flash[:success] = "Success updated Bits Type [#{@type.display_name}]"
        redirect_to bits_types_path
      else
        flash.now[:danger] = @type.errors.full_messages.to_sentence
        render :edit
      end
    end

    protected

    def set_type
      @type = Type.find params[:id]
      authorize @type
    end

    def set_enums
      @entitlement_source_types = Type.entitlement_source_types
      @business_attributions = Type.business_attributions
    end

    def build_type(params)
      Type.new(
        id: params[:id],
        display_name: params[:display_name],
        is_paid: params[:is_paid] == "true",
        is_promotional: params[:is_promotional] == "true",
        cost_per_bits_usc: params[:cost_per_bits_usc].to_f,
        entitlement_source_type: params[:entitlement_source_type].to_sym,
        business_attribution: params[:business_attribution].to_sym
      )
    end

    def type_params
      params.require(:bits_type).permit(:id,
                                        :display_name,
                                        :is_paid,
                                        :is_promotional,
                                        :cost_per_bits_usc,
                                        :entitlement_source_type,
                                        :business_attribution,
                                        :type)
    end
  end
end
