const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');

const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class MessagesDBApi {
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const messages = await db.messages.create(
            {
                id: data.id || undefined,
                body: data.body || null,
                read_at: data.read_at || null,
                created_at_ts: data.created_at_ts || null,
                importHash: data.importHash || null,
                createdById: currentUser.id,
                updatedById: currentUser.id,
            },
            { transaction },
        );

        await messages.setLead( data.lead || null, { transaction });
        await messages.setSender_user( data.sender_user || currentUser.id, { transaction });
        await messages.setReceiver_user( data.receiver_user || null, { transaction });

        return messages;
    }

    static async findAll(filter, options) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;
        offset = currentPage * limit;

        const transaction = (options && options.transaction) || undefined;
        const currentUser = options?.currentUser;

        // Data Isolation
        if (currentUser && currentUser.app_role) {
            const roleName = currentUser.app_role.name;
            if (roleName === 'Verified Business Owner') {
                const businessId = currentUser.businessId;
                if (businessId) {
                    where[Op.or] = [
                        { sender_userId: currentUser.id },
                        { receiver_userId: currentUser.id },
                        { '$lead.lead_matches_lead.businessId$': businessId }
                    ];
                } else {
                    where[Op.or] = [
                        { sender_userId: currentUser.id },
                        { receiver_userId: currentUser.id },
                        { '$lead.lead_matches_lead.business.owner_userId$': currentUser.id }
                    ];
                }
            } else if (roleName === 'Consumer') {
                where[Op.or] = [
                    { sender_userId: currentUser.id },
                    { receiver_userId: currentUser.id },
                    { '$lead.userId$': currentUser.id }
                ];
            }
        }

        let include = [
            {
                model: db.leads,
                as: 'lead',
                required: false,
                include: [{
                    model: db.lead_matches,
                    as: 'lead_matches_lead',
                    include: [{ model: db.businesses, as: 'business' }]
                }],
                where: filter.lead ? {
                    [Op.or]: [
                        { id: { [Op.in]: filter.lead.split('|').map(term => Utils.uuid(term)) } },
                        { keyword: { [Op.or]: filter.lead.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } },
                    ]
                } : undefined,
            },
            {
                model: db.users,
                as: 'sender_user',
                required: false,
                where: filter.sender_user ? {
                    [Op.or]: [
                        { id: { [Op.in]: filter.sender_user.split('|').map(term => Utils.uuid(term)) } },
                        { firstName: { [Op.or]: filter.sender_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } },
                    ]
                } : undefined,
            },
            {
                model: db.users,
                as: 'receiver_user',
                required: false,
                where: filter.receiver_user ? {
                    [Op.or]: [
                        { id: { [Op.in]: filter.receiver_user.split('|').map(term => Utils.uuid(term)) } },
                        { firstName: { [Op.or]: filter.receiver_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } },
                    ]
                } : undefined,
            },
        ];

        if (filter) {
            if (filter.id) where.id = Utils.uuid(filter.id);
            if (filter.body) where.body = { [Op.iLike]: `%${filter.body}%` };
        }

        const queryOptions = {
            where,
            include,
            distinct: true,
            subQuery: false, // Fix for "missing FROM-clause entry" when using limit + nested includes
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction,
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        const { rows, count } = await db.messages.findAndCountAll(queryOptions);

        return {
            rows: options?.countOnly ? [] : rows,
            count: count
        };
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;
        const messages = await db.messages.findOne({ where, transaction });
        if (!messages) return null;

        const output = messages.get({plain: true});
        output.lead = await messages.getLead({ transaction });
        output.sender_user = await messages.getSender_user({ transaction });
        output.receiver_user = await messages.getReceiver_user({ transaction });

        return output;
    }

    static async update(id, data, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        const messages = await db.messages.findByPk(id, {transaction});
        if (!messages) return null;

        const updatePayload = { ...data, updatedById: currentUser.id };
        await messages.update(updatePayload, {transaction});

        if (data.lead !== undefined) await messages.setLead(data.lead, { transaction });
        if (data.sender_user !== undefined) await messages.setSender_user(data.sender_user, { transaction });
        if (data.receiver_user !== undefined) await messages.setReceiver_user(data.receiver_user, { transaction });

        return messages;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;
        const messages = await db.messages.findAll({ where: { id: { [Op.in]: ids } }, transaction });

        for (const record of messages) {
            await record.update({deletedBy: currentUser.id}, {transaction});
            await record.destroy({transaction});
        }
        return messages;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        const messages = await db.messages.findByPk(id, options);
        await messages.update({ deletedBy: currentUser.id }, { transaction });
        await messages.destroy({ transaction });
        return messages;
    }

    static async findAllAutocomplete(query, limit, offset) {
        let where = {};
        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    { ['body']: { [Op.iLike]: `%${query}%` } },
                ],
            };
        }

        const records = await db.messages.findAll({
            attributes: ['id', 'body'],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            order: [['body', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.body,
        }));
    }
};