require "rails_helper"

RSpec.describe Billing::IssueInvoice do
  let(:club) do
    Club.create!(
      name: "Mail Club", sport: "volleyball",
      primary_color: "#e53935", secondary_color: "#ffffff",
      billing_legal_name: "ASD Mail", billing_email: "fatture@test.it",
      billing_address_line: "Via 1", billing_city: "Milano", billing_postal_code: "20100",
      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(:invoice) do
    club.billing_invoices.create!(
      number: "2026/99", issued_on: Date.current, amount_cents: 500,
      currency: "eur", status: "draft", source: "manual", billing_payment: payment
    )
  end
  it "emette la fattura, allega il pdf e invia email" do
    pdf_io = StringIO.new("%PDF-1.4 test\n")

    expect do
      described_class.call(
        invoice: invoice,
        pdf: { io: pdf_io, filename: "fattura-test.pdf", content_type: "application/pdf" }
      )
    end.to change { ActionMailer::Base.deliveries.size }.by(1)

    invoice.reload
    expect(invoice.status).to eq("sent")
    expect(invoice.pdf).to be_attached
    expect(invoice.emailed_at).to be_present
    expect(ActionMailer::Base.deliveries.last.to).to include("fatture@test.it")
  end
end
