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

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

        const safety_policies = await db.safety_policies.create(
            {
                id: data.id || undefined,
        
        policy_name: data.policy_name
        ||
        null
            ,
            
        enforcement_mode: data.enforcement_mode
        ||
        null
            ,
            
        scope: data.scope
        ||
        null
            ,
            
        policy_rules: data.policy_rules
        ||
        null
            ,
            
        restricted_topics: data.restricted_topics
        ||
        null
            ,
            
        never_copy_sources: data.never_copy_sources
        ||
        null
            ,
            
        citation_required: data.citation_required
        ||
        false
        
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return safety_policies;
    }
    

    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 safety_policiesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                policy_name: item.policy_name
            ||
            null
            ,
            
                enforcement_mode: item.enforcement_mode
            ||
            null
            ,
            
                scope: item.scope
            ||
            null
            ,
            
                policy_rules: item.policy_rules
            ||
            null
            ,
            
                restricted_topics: item.restricted_topics
            ||
            null
            ,
            
                never_copy_sources: item.never_copy_sources
            ||
            null
            ,
            
                citation_required: item.citation_required
            ||
            false
        
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return safety_policies;
    }

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

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


        

        const updatePayload = {};
        
        if (data.policy_name !== undefined) updatePayload.policy_name = data.policy_name;
        
        
        if (data.enforcement_mode !== undefined) updatePayload.enforcement_mode = data.enforcement_mode;
        
        
        if (data.scope !== undefined) updatePayload.scope = data.scope;
        
        
        if (data.policy_rules !== undefined) updatePayload.policy_rules = data.policy_rules;
        
        
        if (data.restricted_topics !== undefined) updatePayload.restricted_topics = data.restricted_topics;
        
        
        if (data.never_copy_sources !== undefined) updatePayload.never_copy_sources = data.never_copy_sources;
        
        
        if (data.citation_required !== undefined) updatePayload.citation_required = data.citation_required;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return safety_policies;
    }

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

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

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


        return safety_policies;
    }

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

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

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

        await safety_policies.destroy({
            transaction
        });

        return safety_policies;
    }

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

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

        if (!safety_policies) {
            return safety_policies;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.sandbox_scenarios_safety_policy = await safety_policies.getSandbox_scenarios_safety_policy({
            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.policy_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'safety_policies',
                        'policy_name',
                        filter.policy_name,
                    ),
                };
            }
            
            if (filter.policy_rules) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'safety_policies',
                        'policy_rules',
                        filter.policy_rules,
                    ),
                };
            }
            
            if (filter.restricted_topics) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'safety_policies',
                        'restricted_topics',
                        filter.restricted_topics,
                    ),
                };
            }
            
            if (filter.never_copy_sources) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'safety_policies',
                        'never_copy_sources',
                        filter.never_copy_sources,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.enforcement_mode) {
                where = {
                    ...where,
                enforcement_mode: filter.enforcement_mode,
            };
            }
            
            if (filter.scope) {
                where = {
                    ...where,
                scope: filter.scope,
            };
            }
            
            if (filter.citation_required) {
                where = {
                    ...where,
                citation_required: filter.citation_required,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_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.safety_policies.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(
                        'safety_policies',
                        'policy_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

