require "rails_helper"

RSpec.describe Billing::AttachPaymentInvoice do
  let!(:club) do
    Club.create!(
      name: "Attach Club", sport: "volleyball",
      primary_color: "#e53935", secondary_color: "#ffffff",
      billing_entity_type: "company", billing_legal_name: "ASD Attach",
      billing_email: "fatture@attach.test", billing_address_line: "Via 1",
      billing_city: "Milano", billing_province: "MI", billing_postal_code: "20100",
      billing_country: "IT", billing_vat_number: "12345678901",
      billing_recipient_code: "ABCDEFG"
    )
  end
  let!(:payment) do
    club.billing_payments.create!(
      amount_cents: 500, currency: "eur", status: "paid", paid_at: Time.current,
      description: "Premium Light — €5/mese"
    )
  end
  let(:pdf) do
    { io: StringIO.new("%PDF-1.4 test"), filename: "fattura.pdf", content_type: "application/pdf" }
  end

  it "crea fattura, allega PDF e invia email" do
    mail = instance_double(ActionMailer::MessageDelivery, deliver_now: true)
    allow(Billing::InvoiceMailer).to receive(:with).and_return(
      instance_double(Billing::InvoiceMailer, invoice_pdf: mail)
    )

    expect {
      described_class.call(payment: payment, pdf: pdf)
    }.to change { club.billing_invoices.count }.by(1)

    inv = payment.reload.invoice
    expect(inv.pdf).to be_attached
    expect(inv.status).to eq("sent")
    expect(Billing::InvoiceMailer).to have_received(:with).with(invoice: inv)
  end
end
