require "rails_helper"

RSpec.describe Billing::Stripe::RecordPayment do
  let(:club) { Club.create!(name: "Pay Club", sport: "volleyball", primary_color: "#e53935", secondary_color: "#ffffff") }

  before do
    load Rails.root.join("db/seeds/plans.rb")
    allow(MatchLiveTv).to receive(:stripe_premium_light_yearly_price_id).and_return("price_light_y")
    Billing::AssignPlan.call(club: club, plan_slug: "premium_light", stripe_attrs: { stripe_subscription_id: "sub_x" })
  end

  it "crea un pagamento da fattura Stripe" do
    invoice = double(
      id: "in_test_1",
      metadata: { "club_id" => club.id, "plan_slug" => "premium_light", "billing_interval" => "yearly" },
      parent: nil,
      amount_paid: 4000,
      currency: "eur",
      status: "paid",
      description: "Premium Light",
      invoice_pdf: "https://stripe.com/invoice.pdf",
      hosted_invoice_url: "https://stripe.com/hosted",
      status_transitions: double(paid_at: Time.current.to_i),
      lines: double(data: [
        double(
          description: "Premium Light annuale",
          metadata: { "plan_slug" => "premium_light", "billing_interval" => "yearly" },
          pricing: double(price_details: double(price: "price_light_y"))
        )
      ])
    )
    allow(invoice).to receive(:metadata).and_return({ "club_id" => club.id, "plan_slug" => "premium_light", "billing_interval" => "yearly" })
    allow(Stripe::Invoice).to receive(:retrieve).and_return(invoice)

    payment = described_class.call(stripe_invoice: invoice)

    expect(payment).to be_persisted
    expect(payment.club).to eq(club)
    expect(payment.amount_cents).to eq(4000)
    expect(payment.stripe_invoice_id).to eq("in_test_1")
    expect(payment.description).to eq("Premium Light — €40/anno")
  end
end
