module Public
  class ClubBillingController < WebBaseController
    before_action :require_login!
    before_action :set_club
    before_action :require_club_owner_for_club!

    def profile
    end

    def update_profile
      @club.assign_attributes(billing_profile_params)
      if @club.save(context: :billing_profile)
        if premium_checkout_return_params.present? && @club.billing_profile_complete?
          redirect_to public_club_checkout_path(
            @club,
            plan: premium_checkout_return_params[:plan],
            interval: premium_checkout_return_params[:interval]
          ), notice: "Dati salvati. Procedi con il pagamento."
        else
          redirect_to public_club_billing_path(@club), notice: "Dati di fatturazione aggiornati."
        end
      else
        flash.now[:alert] = @club.errors.full_messages.join(", ")
        render :profile, status: :unprocessable_entity
      end
    end

    def cancel_subscription
      unless MatchLiveTv.stripe_enabled?
        redirect_to public_club_billing_path(@club), alert: "Stripe non configurato."
        return
      end

      Billing::Stripe::CancelSubscription.call(club: @club)
      sub = @club.subscription.reload
      date = sub.current_period_end ? helpers.l_local(sub.current_period_end.to_date) : "fine periodo"
      redirect_to public_club_billing_path(@club),
                  notice: "Abbonamento disdetto. Resta attivo fino al #{date}; da quel giorno passerai al piano Free."
    rescue ArgumentError, RuntimeError => e
      redirect_to public_club_billing_path(@club), alert: e.message
    rescue ::Stripe::StripeError => e
      redirect_to public_club_billing_path(@club), alert: "Errore Stripe: #{e.message}"
    end

    def download_invoice
      invoice = @club.billing_invoices.find(params[:invoice_id])
      unless invoice.pdf.attached?
        redirect_to public_club_billing_path(@club), alert: "PDF fattura non disponibile."
        return
      end

      redirect_to rails_blob_path(invoice.pdf, disposition: "attachment"), allow_other_host: true
    end

    private

    def set_club
      @club = current_user.owned_clubs.find(params[:id])
    end

    def require_club_owner_for_club!
      require_club_owner!(@club)
    end

    def premium_checkout_return_params
      plan = params[:plan].presence_in(%w[premium_light premium_full])
      return nil if plan.blank?

      {
        plan: plan,
        interval: params[:interval].presence || Billing::Stripe::PriceCatalog::DEFAULT_INTERVAL
      }
    end

    def billing_profile_params
      params.require(:club).permit(
        :billing_entity_type,
        :billing_legal_name,
        :billing_vat_number,
        :billing_fiscal_code,
        :billing_email,
        :billing_phone,
        :billing_address_line,
        :billing_city,
        :billing_province,
        :billing_postal_code,
        :billing_country,
        :billing_recipient_code,
        :billing_pec
      )
    end
  end
end
