class Pdf::Accounting::InvoiceService < Pdf::NewApplicationService
  def initialize(school, invoice_id)
    @invoice_id = invoice_id
    @school = school
    @family = invoice.family.decorate
  end

  private
    def header
      content = ActionController::Base.new.render_to_string(
        partial: 'pdf/headers/school_info.html.haml',
        locals: {
          school: @school,
          side_content_partial: 'pdf/accounting/invoice_header',
          side_content: { invoice: invoice }
        }
      )
      { content: content, spacing: 25 }
    end

    def body
      ActionController::Base.new.render_to_string(
        partial: 'pdf/accounting/invoice.html.haml',
        locals: {
          invoice: invoice,
          family: @family,
          charges: charges.decorate,
          include_allocations: invoice_config.include_allocations,
          allocations: allocations
        }
      )
    end

    def invoice
      @invoice ||= @school.accounting_invoices
        .includes(:charges, { transaction_details: :increase_allocations })
        .find_by(id: @invoice_id)
        .decorate
    end

    def invoice_config
      @invoice_config ||= @school.find_or_build_accounting_invoice_config
    end

    def charges
      @invoice.charges
        .includes(:students, transaction_details: [
          :increase_allocations,
          { subcategory: :category }
        ])
    end

    def allocations
      @allocations ||= invoice.allocations.includes(decrease: :accounting_transaction)
    end
end
