require "rails_helper"

RSpec.describe Billing::Stripe::FinalizeSubscription do
  let(:club) do
    Club.create!(
      name: "Fin Club", sport: "volleyball",
      primary_color: "#e53935", secondary_color: "#ffffff"
    )
  end

  before { load Rails.root.join("db/seeds/plans.rb") }

  it "passa a free quando il periodo è scaduto e la disdetta era programmata" do
    Billing::AssignPlan.call(
      club: club,
      plan_slug: "premium_light",
      status: "active",
      stripe_attrs: {
        stripe_subscription_id: "sub_fin",
        cancel_at_period_end: true,
        current_period_end: 1.day.ago
      }
    )
    stripe_sub = double(
      id: "sub_fin",
      status: "active",
      cancel_at_period_end: true
    )
    allow(Stripe::Subscription).to receive(:retrieve).with("sub_fin").and_return(stripe_sub)
    allow(Billing::Stripe::SubscriptionPeriod).to receive(:times).and_return([2.months.ago, 1.day.ago])

    expect(described_class.call(club: club)).to be true
    expect(club.reload.subscription.plan.slug).to eq("free")
    expect(club.subscription.stripe_subscription_id).to be_nil
  end

  it "non cambia piano se il periodo non è ancora scaduto" do
    Billing::AssignPlan.call(
      club: club,
      plan_slug: "premium_light",
      status: "active",
      stripe_attrs: {
        stripe_subscription_id: "sub_ok",
        cancel_at_period_end: true,
        current_period_end: 1.month.from_now
      }
    )
    stripe_sub = double(id: "sub_ok", status: "active", cancel_at_period_end: true)
    allow(Stripe::Subscription).to receive(:retrieve).and_return(stripe_sub)

    expect(described_class.call(club: club)).to be false
    expect(club.reload.subscription.plan.slug).to eq("premium_light")
  end
end
