module Billing
  module Stripe
    # Garantisce un Customer Stripe valido per la modalità API attiva (test vs live).
    class EnsureCustomer
      def self.call(club:, user:)
        new(club: club, user: user).call
      end

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

      def call
        sub = @club.subscription || @club.build_subscription(plan: Plan["free"], status: "active")

        if sub.stripe_customer_id.present? && !customer_valid?(sub.stripe_customer_id)
          reset_stripe_billing!(sub)
        end

        return sub.stripe_customer_id if sub.stripe_customer_id.present?

        customer = ::Stripe::Customer.create(
          email: billing_email,
          name: @club.billing_legal_name.presence || @club.name,
          metadata: { club_id: @club.id }
        )
        sub.update!(stripe_customer_id: customer.id)
        customer.id
      end

      private

      def billing_email
        @club.billing_email.presence || @user.email
      end

      def customer_valid?(customer_id)
        ::Stripe::Customer.retrieve(customer_id)
        true
      rescue ::Stripe::InvalidRequestError => e
        return false if e.code == "resource_missing" || e.message.include?("No such customer")

        raise
      end

      def reset_stripe_billing!(sub)
        Rails.logger.info(
          "[Stripe] Customer #{sub.stripe_customer_id} non valido per club #{@club.id} — reset ID Stripe locali"
        )
        sub.update!(
          stripe_customer_id: nil,
          stripe_subscription_id: nil,
          cancel_at_period_end: false
        )
      end
    end
  end
end
