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

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

        await verification_evidences.setSubmission( data.submission || null, { transaction });
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.verification_evidences.getTableName(),
                belongsToColumn: 'files',
                belongsToId: verification_evidences.id,
            },
            data.files,
            options,
        );

        return verification_evidences;
    }

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

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

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

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

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

        const output = verification_evidences.get({plain: true});
        output.submission = await verification_evidences.getSubmission({ transaction });
        output.files = await verification_evidences.getFiles({ transaction });

        return output;
    }

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

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

        if (data.submission !== undefined) await verification_evidences.setSubmission(data.submission, { transaction });
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.verification_evidences.getTableName(),
                belongsToColumn: 'files',
                belongsToId: verification_evidences.id,
            },
            data.files,
            options,
        );

        return verification_evidences;
    }

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

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

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

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

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