const models = require('vn-loopback/server/server').models;

const invoiceInId = 1;
const supplierId = 791;
describe('invoiceIn updateInvoiceIn()', () => {
    const ctx = beforeAll.getCtx();
    let options;
    let tx;

    beforeEach(async() => {
        options = {transaction: tx};
        tx = await models.Sale.beginTransaction({});
        options.transaction = tx;
    });

    afterEach(async() => {
        await tx.rollback();
    });

    it('should update the invoice', async() => {
        const invoiceBefore = await models.InvoiceIn.findById(invoiceInId, null, options);
        await update(ctx, options);
        const invoiceAfter = await models.InvoiceIn.findById(invoiceInId, null, options);

        expect(invoiceAfter.supplierFk).not.toBe(invoiceBefore.supplierFk);
        expect(invoiceAfter.supplierFk).toBe(supplierId);
    });

    it('should not update the invoice if is booked', async() => {
        let error;
        try {
            await models.InvoiceIn.toBook(ctx, invoiceInId, options);
            await update(ctx, options);
        } catch (e) {
            error = e;
        }

        expect(error.message).toBe('InvoiceIn is already booked');
    });
});

async function update(ctx, opts) {
    const supplierRef = 'mockRef';
    const currencyId = 1;
    await models.InvoiceIn.updateInvoiceIn(ctx,
        invoiceInId,
        supplierId,
        supplierRef,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        currencyId,
        undefined,
        undefined,
        opts);
}