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

describe('Chat notifyIssue()', () => {
    const ctx = {req: {accessToken: {userId: 1}}};
    ctx.req.__ = value => {
        return value;
    };
    const chatModel = models.Chat;
    const osTicketModel = models.OsTicket;
    const departmentId = 31;

    it(`should not call to the send() method and neither return a response`, async() => {
        spyOn(chatModel, 'send').and.callThrough();
        spyOn(osTicketModel, 'rawSql').and.returnValue([]);

        await chatModel.notifyIssues(ctx);

        expect(chatModel.send).not.toHaveBeenCalled();
    });

    it(`should return a response calling the send() method`, async() => {
        spyOn(chatModel, 'send').and.callThrough();
        spyOn(osTicketModel, 'rawSql').and.returnValue([{
            id: 1,
            number: '00001',
            username: 'batman',
            subject: 'Issue title'}
        ]);
        // eslint-disable-next-line max-len
        const expectedMessage = `@all ➔ There's a new urgent ticket:\r\n[ID: 00001 - Issue title @batman](https://cau.verdnatura.es/scp/tickets.php?id=1)`;

        const department = await models.Department.findById(departmentId);
        let orgChatName = department.chatName;
        await department.updateAttribute('chatName', 'IT');

        await chatModel.notifyIssues(ctx);

        expect(chatModel.send).toHaveBeenCalledWith(ctx, '#IT', expectedMessage);

        // restores
        await department.updateAttribute('chatName', orgChatName);
    });
});