module Subscriptions
  class TicketProductsController < Subscriptions::BaseController

    AUDIT_ACTION_UPDATE = "update"
    AUDIT_TICKET_PRODUCT = "ticket_product"
    AUDIT_LDAP_USER = "ldap_user"

    def index
      authorize TicketProduct

      @ticket_products = TicketProduct.search({
        login: params[:login],
        channel_id: params[:channel_id],
        short_name: params[:short_name]
      })

      track_action! trackable_request
        .assemble_an
        .admin_panel_ticket_product_search(
          product_owner_login: params[:product_owner_login],
          product_owner_id: params[:product_owner_id],
          product_short_name: params[:product_short_name]
        )
    end

    def show
      authorize TicketProduct

      @emote_uploader = Mako::EmoteUploader.new
      @ticket_product = TicketProduct.find(params[:id])

      unless @ticket_product.persisted?
        flash[:error] = "No ticket product found with ID #{params[:id]}"
        redirect_to subscriptions_ticket_products_path
      end

      begin
        mako_emotes = Mako::Emote.get_emoticons_by_group(@ticket_product.emoticon_set["id"].to_s)
      rescue StandardError
        flash[:error] = "Failed to load emotes for this ticket product"
        redirect_to subscriptions_ticket_products_path
      end
      @emotes = mako_emotes
    end

    def edit
      authorize TicketProduct

      @ticket_product = TicketProduct.find(params[:id])
      @emote_prefix = nil
      if @ticket_product.channel_id
        @emote_prefix = Mako::EmotePrefix.get_prefix(@ticket_product.channel_id)
        @emote_prefix.channel_id = @ticket_product.channel_id
      end
    end

    def update
      authorize TicketProduct
      form_params = params[:subscriptions_ticket_product]

      recurring = false
      if form_params[:recurring] == "1"
        recurring = true
      end

      new_fields = {
        id: form_params[:id],
        name: form_params[:name],
        rev_share: form_params[:rev_share],
        interval_unit: form_params[:interval_unit],
        ticket_access_start: form_params[:ticket_access_start],
        ticket_access_end: form_params[:ticket_access_end],
        desc_invoice: form_params[:desc_invoice],
        desc_checkout: form_params[:desc_checkout],
        paywall_html: form_params[:paywall_html],
        paywall_css: form_params[:paywall_css],
        bitrate_access_string: form_params[:bitrate_access_string],
        recurring: recurring
      }

      ticket_product = TicketProduct.find(params[:id])

      old_fields = {
        id: ticket_product.id,
        name: ticket_product.name,
        rev_share: ticket_product.rev_share,
        interval_unit: ticket_product.interval_unit,
        ticket_access_start: ticket_product.ticket_access_start,
        ticket_access_end: ticket_product.ticket_access_end,
        desc_invoice: ticket_product.desc_invoice,
        desc_checkout: ticket_product.desc_checkout,
        paywall_html: ticket_product.paywall_html,
        paywall_css: ticket_product.paywall_css,
        bitrate_access_string: ticket_product.bitrate_access_string,
        recurring: ticket_product.recurring
      }

      response = ticket_product.update(new_fields)
      if response.success?
        audit_ticket_product(old_fields, new_fields)
        flash[:success] = "Successfully updated ticket_product"
      else
        flash[:error] = "Failed to update ticket_product"
      end
      redirect_back
    end

    def deactivate
      authorize TicketProduct

      ticket_product = TicketProduct.find(params[:ticket_product_id])

      response = ticket_product.deactivate(params[:ticket_product_id])
      if response.success?
        flash[:success] = "Successfully deactivated ticket product"
      else
        flash[:error] = "Failed to deactivate ticket product"
      end
      redirect_back
    end

    def reactivate
      authorize TicketProduct

      ticket_product = TicketProduct.find(params[:ticket_product_id])

      response = ticket_product.reactivate(params[:ticket_product_id])
      if response.success?
        flash[:success] = "Successfully reactivated ticket product"
      else
        flash[:error] = "Failed to reactivate ticket product"
      end
      redirect_back
    end

    def grant_admin_sub
      authorize TicketProduct

      ticket_product = TicketProduct.find(params[:ticket_product_id])
      form_params = params[:subscriptions_ticket_product]
      user_login = form_params[:subber]
      user = Twitch::User.find_by_login(user_login)
      if user.blank?
        flash[:error] = "Failed to grant sub: User does not exist"
        return redirect_back
      end

      begin
        Substwirp::AdminSubscription.grant_admin_subscription(user.id.to_s, params[:ticket_product_id].to_s)
      rescue StandardError => e
        flash[:error] = "Failed to grant sub: #{e.message}"
        return redirect_back
      end

      flash[:success] = "Successfully granted #{user_login} a sub to #{params[:ticket_product_id]}"

      track_action! trackable_request
        .assemble_an
        .admin_panel_benefit_grant(
          ticket_product_id: params[:ticket_product_id],
          recipient_login: user_login,
          payment_provider: "admin",
          product_type: "channel_sub"
        )
      redirect_back
    end

    def mass_dnr
      authorize TicketProduct

      admin_email = current_user.email
      ticket_product = TicketProduct.find(params[:ticket_product_id])

      response = ticket_product.mass_dnr(admin_email, params[:ticket_product_id])
      if response.success?
        flash[:success] = "Initiated Mass DNR on ticket_product #{params[:ticket_product_id]}"
      else
        flash[:error] = "Failed to initiate Mass DNR"
      end
      redirect_back
    end

    def create_additional_tiers
      authorize TicketProduct

      response = TicketProduct.create_additional_tiers(params[:ticket_product_id])
      if response.success?
        flash[:success] = response.body["message"]
        begin
          ticket_product = TicketProduct.find(params[:ticket_product_id])
          tier3_product_id = response.body["message"].split(" ").last
          Substwirp::AdminSubscription.grant_admin_subscription(ticket_product.channel_id, tier3_product_id)
        rescue StandardError => e
          flash[:error] = "Could not grant admin sub to product owner: #{e}"
        end
      else
        flash[:error] = response.body["error"]
      end
      redirect_back
    end

    def sync_external_ticket_product
      authorize TicketProduct

      response = Payments::SyncTicketProduct.do(params[:ticket_product_id])
      redirect_to subscriptions_ticket_products_path
    end

    protected

    def audit_ticket_product(prev_ticket_product_params, curr_ticket_product_params)
      update_attributes = [:name, :rev_share, :interval_unit, :ticket_access_start, :ticket_access_end, :desc_invoice, :desc_checkout, :paywall_html, :paywall_css, :bitrate_access_string, :recurring]
      changes = []

      curr_ticket_product_params.each do |key, _|
        symbol = key.to_sym
        change = History::ChangeSet.new(
          attribute: symbol,
          old_value: prev_ticket_product_params[symbol],
          new_value: curr_ticket_product_params[symbol]
        )
        changes.push(change)
      end

      audit = History::Audit.new(
        action: AUDIT_ACTION_UPDATE,
        user_type: AUDIT_LDAP_USER,
        user_id: current_user.ldap_login,
        resource_type: AUDIT_TICKET_PRODUCT,
        resource_id: curr_ticket_product_params[:id],
        changes: changes
      )

      History::AddAudit.add(audit)
    end
  end
end
