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

describe('docuware upload()', () => {
    const userId = 9;
    const ticketIds = [10];
    const ctx = {
        args: {ticketIds},
        req: {
            getLocale: () => {
                return 'en';
            },
            accessToken: {userId: userId},
            headers: {origin: 'http://localhost:5000'},
        }
    };

    const docuwareModel = models.Docuware;
    const ticketModel = models.Ticket;
    const fileCabinetName = 'deliveryNote';

    beforeAll(() => {
        spyOn(docuwareModel, 'getFileCabinet').and.returnValue(new Promise(resolve => resolve(Math.random())));
        spyOn(docuwareModel, 'getDialog').and.returnValue(new Promise(resolve => resolve(Math.random())));
    });

    it('should try upload file', async() => {
        const tx = await models.Docuware.beginTransaction({});
        spyOn(ticketModel, 'deliveryNotePdf').and.returnValue(new Promise(resolve => resolve({})));

        let error;
        try {
            const options = {transaction: tx};
            const user = await models.UserConfig.findById(userId, null, options);
            await user.updateAttribute('tabletFk', 'Tablet1', options);
            await models.Docuware.upload(ctx, ticketIds, fileCabinetName, options);

            await tx.rollback();
        } catch (e) {
            error = e;
            await tx.rollback();
        }

        expect(error.message).toEqual('Action not allowed on the test environment');
    });

    it('should throw error when not have tablet assigned', async() => {
        const tx = await models.Docuware.beginTransaction({});
        spyOn(ticketModel, 'deliveryNotePdf').and.returnValue(new Promise(resolve => resolve({})));

        let error;
        try {
            const options = {transaction: tx};
            await models.Docuware.upload(ctx, ticketIds, fileCabinetName, options);

            await tx.rollback();
        } catch (e) {
            error = e;
            await tx.rollback();
        }

        expect(error.message).toEqual('This user does not have an assigned tablet');
    });
});