require "rails_helper"

RSpec.describe Billing::Stripe::CancelSubscription do
  let(:club) do
    Club.create!(
      name: "Cancel Club", sport: "volleyball",
      primary_color: "#e53935", secondary_color: "#ffffff",
      billing_legal_name: "ASD", billing_email: "b@test.it",
      billing_address_line: "Via 1", billing_city: "Milano", billing_postal_code: "20100",
      billing_vat_number: "12345678901", billing_recipient_code: "ABCDEFG"
    )
  end

  before do
    load Rails.root.join("db/seeds/plans.rb")
    allow(MatchLiveTv).to receive(:stripe_enabled?).and_return(true)
    Billing::AssignPlan.call(
      club: club,
      plan_slug: "premium_light",
      status: "active",
      stripe_attrs: {
        stripe_subscription_id: "sub_cancel",
        stripe_customer_id: "cus_x",
        current_period_end: 1.month.from_now,
        billing_interval: "monthly"
      }
    )
  end

  it "programma la disdetta a fine periodo su Stripe" do
    stripe_sub = double(
      id: "sub_cancel",
      customer: "cus_x",
      status: "active",
      cancel_at_period_end: true,
      metadata: { "club_id" => club.id, "plan_slug" => "premium_light", "billing_interval" => "monthly" },
      items: double(data: [double(price: double(id: "price_m", recurring: double(interval: "month")))])
    )
    allow(Stripe::Subscription).to receive(:update).with("sub_cancel", cancel_at_period_end: true).and_return(stripe_sub)
    allow(Billing::Stripe::CheckoutSync).to receive(:from_subscription)
    allow(Billing::Stripe::SubscriptionPeriod).to receive(:times).and_return([Time.current, 1.month.from_now])

    described_class.call(club: club)

    expect(Stripe::Subscription).to have_received(:update).with("sub_cancel", cancel_at_period_end: true)
    expect(Billing::Stripe::CheckoutSync).to have_received(:from_subscription).with(stripe_sub, club: club)
  end

  it "rifiuta se la disdetta è già programmata" do
    club.subscription.update!(cancel_at_period_end: true)
    expect { described_class.call(club: club) }.to raise_error(/già programmata/)
  end
end
