module Billing
  class AttachPaymentInvoice
    class Error < StandardError; end

    def self.call(payment:, pdf:)
      new(payment: payment, pdf: pdf).call
    end

    def initialize(payment:, pdf:)
      @payment = payment
      @pdf = pdf
    end

    def call
      raise Error, "Seleziona un file PDF" if @pdf.blank?
      raise Error, "Pagamento non valido" unless @payment.status == "paid"

      club = @payment.club
      invoice = @payment.invoice || build_invoice!(club)
      IssueInvoice.call(invoice: invoice, pdf: @pdf)
    end

    private

    def build_invoice!(club)
      club.billing_invoices.create!(
        number: InvoiceNumber.next_for(club),
        issued_on: @payment.paid_at&.to_date || Date.current,
        amount_cents: @payment.amount_cents,
        currency: @payment.currency.presence || "eur",
        status: "draft",
        source: "manual",
        billing_payment: @payment
      )
    end
  end
end
