module Billing
  module Stripe
    # Sincronizza solo dati di fatturazione (mai dati carta) sul Customer Stripe.
    class CustomerSync
      def self.call(club:, customer_id:)
        new(club: club, customer_id: customer_id).call
      end

      def initialize(club:, customer_id:)
        @club = club
        @customer_id = customer_id
      end

      def call
        return @customer_id if @customer_id.blank?

        ::Stripe::Customer.update(@customer_id, customer_attributes)
        @customer_id
      end

      private

      def customer_attributes
        attrs = {
          name: @club.billing_legal_name.presence || @club.name,
          email: @club.billing_email.presence,
          metadata: { club_id: @club.id },
          address: {
            line1: @club.billing_address_line,
            city: @club.billing_city,
            state: @club.billing_province,
            postal_code: @club.billing_postal_code,
            country: @club.billing_country.presence || "IT"
          }
        }
        attrs[:address] = nil if attrs[:address].values.all?(&:blank?)
        attrs.compact
      end
    end
  end
end
