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

      def initialize(club:)
        @club = club
      end

      def call
        raise "Stripe non configurato" unless MatchLiveTv.stripe_enabled?

        sub = @club.subscription
        raise "Nessun abbonamento premium attivo" unless sub&.premium? && sub.stripe_subscription_id.present?
        raise "Disdetta già programmata" if sub.cancel_at_period_end?

        stripe_sub = ::Stripe::Subscription.update(
          sub.stripe_subscription_id,
          cancel_at_period_end: true
        )

        CheckoutSync.from_subscription(stripe_sub, club: @club)
        @club.subscription.reload
      end
    end
  end
end
