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

        const business_badges = await db.business_badges.create(
            {
                id: data.id || undefined,
                badge_type: data.badge_type || null,
                status: data.status || null,
                granted_at: data.granted_at || null,
                revoked_at: data.revoked_at || null,
                notes: data.notes || null,
                created_at_ts: data.created_at_ts || null,
                updated_at_ts: data.updated_at_ts || null,
                importHash: data.importHash || null,
                createdById: currentUser.id,
                updatedById: currentUser.id,
            },
            { transaction },
        );

        await business_badges.setBusiness( data.business || null, { transaction });

        return business_badges;
    }

    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}%` })) } },
                    ]
                } : {},
            },
        ];

        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_badges.findAndCountAll(queryOptions);

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

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

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

        return output;
    }

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

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

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

        return business_badges;
    }

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

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

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

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

        const records = await db.business_badges.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,
        }));
    }
};