import { Injectable, Inject } from '@nestjs/common'
import { QuickBooksService } from './quickbooks.service'
import { AxiosInstance } from 'axios'

@Injectable()
export class InvoiceService {
    constructor(
        private readonly quickBooksService: QuickBooksService,
        @Inject('QUICKBOOKS_API') private readonly quickbooksApi: AxiosInstance
    ) {}

	async getInvoice(invoiceId: string) {
        try {
			const response = await this.quickbooksApi.get(`invoice/${invoiceId}`)
			return response.data?.Invoice
        } catch (error) {
            throw new Error(`Failed to get invoice ${invoiceId}: ${error.message}`)
        }
	}

	async addPaymentLinkToInvoice(invoice: any, paymentLink: any) {
		try {
            const invoiceData = {
                ...invoice,
                // CustomField: [
                //     {
                //         DefinitionId: '1',
                //         Name: 'Payment Link',
                //         Type: 'StringType',
                //         StringValue: paymentLink?.url,
                //     },
                // ],
                CustomerMemo: {
                    value: `Click here to pay: ${paymentLink?.url}`,
                },
            }
    
            const response = await this.quickbooksApi.post(`invoice`, invoiceData)
    
            return response.data
        } catch (error) {
            throw new Error(`Failed to add payment link to invoice ${invoice?.Id}: ${error.message}`)
        }
	}
}
