
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 StandardsDBApi {
    

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

        const standards = await db.standards.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        short_name: data.short_name
        ||
        null
            ,
            
        version: data.version
        ||
        null
            ,
            
        publisher: data.publisher
        ||
        null
            ,
            
        scope_notes: data.scope_notes
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return standards;
    }
    

    static async bulkImport(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        // Prepare data - wrapping individual data transformations in a map() method
        const standardsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                short_name: item.short_name
            ||
            null
            ,
            
                version: item.version
            ||
            null
            ,
            
                publisher: item.publisher
            ||
            null
            ,
            
                scope_notes: item.scope_notes
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const standards = await db.standards.bulkCreate(standardsData, { transaction });

        // For each item created, replace relation files
        

        return standards;
    }

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

        const standards = await db.standards.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.short_name !== undefined) updatePayload.short_name = data.short_name;
        
        
        if (data.version !== undefined) updatePayload.version = data.version;
        
        
        if (data.publisher !== undefined) updatePayload.publisher = data.publisher;
        
        
        if (data.scope_notes !== undefined) updatePayload.scope_notes = data.scope_notes;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

        await standards.update(updatePayload, {transaction});

        
        

        
        

        

        return standards;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const standards = await db.standards.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of standards) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of standards) {
                await record.destroy({transaction});
            }
        });


        return standards;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const standards = await db.standards.findByPk(id, options);

        await standards.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await standards.destroy({
            transaction
        });

        return standards;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const standards = await db.standards.findOne(
            { where },
            { transaction },
        );

        if (!standards) {
            return standards;
        }

        const output = standards.get({plain: true});

        
        
        
        
        
        
        output.clauses_standard = await standards.getClauses_standard({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        return output;
    }

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

        

        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'standards',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.short_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'standards',
                        'short_name',
                        filter.short_name,
                    ),
                };
            }
            
            if (filter.version) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'standards',
                        'version',
                        filter.version,
                    ),
                };
            }
            
            if (filter.publisher) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'standards',
                        'publisher',
                        filter.publisher,
                    ),
                };
            }
            
            if (filter.scope_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'standards',
                        'scope_notes',
                        filter.scope_notes,
                    ),
                };
            }
            

            
            

            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.active,
            };
            }
            




            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }
        

        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

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

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

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'standards',
                        'short_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

