require "rails_helper"

RSpec.describe Billing::Stripe::CheckoutSession do
  let(:user) { User.create!(email: "checkout@test.it", name: "Owner", password: "password123", role: "coach") }
  let(:club) do
    Club.create!(
      name: "Checkout Club", sport: "volleyball",
      primary_color: "#e53935", secondary_color: "#ffffff",
      billing_legal_name: "ASD Checkout", billing_email: "bill@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)
    allow(MatchLiveTv).to receive(:stripe_premium_light_yearly_price_id).and_return("price_light_y")
    allow(MatchLiveTv).to receive(:stripe_premium_light_monthly_price_id).and_return("price_light_m")
    allow(MatchLiveTv).to receive(:stripe_premium_full_yearly_price_id).and_return("price_full_y")
    allow(MatchLiveTv).to receive(:stripe_premium_full_monthly_price_id).and_return("price_full_m")
    allow(MatchLiveTv).to receive(:app_public_url).and_return("http://localhost:3000")
  end

  it "crea checkout annuale" do
    session = double(url: "https://checkout.stripe.com/yearly")
    expect(Stripe::Customer).to receive(:create).and_return(double(id: "cus_new"))
    expect(Billing::Stripe::CustomerSync).to receive(:call).with(club: club, customer_id: "cus_new")
    expect(Stripe::Checkout::Session).to receive(:create).with(
      hash_including(
        line_items: [{ price: "price_light_y", quantity: 1 }],
        metadata: hash_including(plan_slug: "premium_light", billing_interval: "yearly"),
        subscription_data: { metadata: hash_including(billing_interval: "yearly") }
      )
    ).and_return(session)

    url = described_class.new(club: club, user: user, plan_slug: "premium_light", interval: "yearly").url
    expect(url).to eq("https://checkout.stripe.com/yearly")
  end

  it "crea checkout mensile" do
    session = double(url: "https://checkout.stripe.com/monthly")
    allow(Stripe::Customer).to receive(:create).and_return(double(id: "cus_m"))
    allow(Billing::Stripe::CustomerSync).to receive(:call)
    expect(Stripe::Checkout::Session).to receive(:create).with(
      hash_including(line_items: [{ price: "price_light_m", quantity: 1 }])
    ).and_return(session)

    url = described_class.new(club: club, user: user, plan_slug: "premium_light", interval: "monthly").url
    expect(url).to eq("https://checkout.stripe.com/monthly")
  end
end
