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 Business_categoriesDBApi {
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

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

        await business_categories.setBusiness( data.business || null, { transaction });
        await business_categories.setCategory( data.category || null, { transaction });

        return business_categories;
    }

    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') {
                if (currentUser.businessId) {
                    where.businessId = currentUser.businessId;
                } else {
                    where['$business.owner_userId$'] = currentUser.id;
                }
            }
        }

        let include = [
            {
                model: db.businesses,
                as: 'business',
                where: filter.business ? {
                    [Op.or]: [
                        { id: { [Op.in]: filter.business.split('|').map(term => Utils.uuid(term)) } },
                        { name: { [Op.or]: filter.business.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } },
                    ]
                } : {},
            },
            {
                model: db.categories,
                as: 'category',
                where: filter.category ? {
                    [Op.or]: [
                        { id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
                        { name: { [Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } },
                    ]
                } : {},
            },
        ];

        if (filter) {
            if (filter.id) where.id = Utils.uuid(filter.id);
        }

        const queryOptions = {
            where,
            include,
            distinct: true,
            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.business_categories.findAndCountAll(queryOptions);

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

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

        const output = business_categories.get({plain: true});
        output.business = await business_categories.getBusiness({ transaction });
        output.category = await business_categories.getCategory({ transaction });

        return output;
    }

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

        const updatePayload = { updatedById: currentUser.id };
        if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
        await business_categories.update(updatePayload, {transaction});

        if (data.business !== undefined) await business_categories.setBusiness(data.business, { transaction });
        if (data.category !== undefined) await business_categories.setCategory(data.category, { transaction });

        return business_categories;
    }

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

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

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

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

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

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