module Billing
  module Stripe
    class SyncPayments
      def self.call(club:)
        new(club: club).call
      end

      def initialize(club:)
        @club = club
      end

      def call
        customer_id = @club.subscription&.stripe_customer_id
        return 0 if customer_id.blank?

        count = 0
        starting_after = nil

        loop do
          # Lista senza expand profondo (limite Stripe 4 livelli); RecordPayment arricchisce ogni fattura.
          list = ::Stripe::Invoice.list(customer: customer_id, limit: 25, starting_after: starting_after)
          list.data.each do |invoice|
            next unless invoice.status == "paid"

            RecordPayment.call(stripe_invoice: invoice, club: @club)
            count += 1
          end
          break unless list.has_more

          starting_after = list.data.last.id
        end

        # Allinea anche piano/intervallo da abbonamento Stripe attivo (non solo lo storico pagamenti).
        CheckoutSync.call(club: @club)

        count
      end
    end
  end
end
