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

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

        const clauses = await db.clauses.create(
            {
                id: data.id || undefined,
        
        clause_code: data.clause_code
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        text_excerpt: data.text_excerpt
        ||
        null
            ,
            
        guidance_notes: data.guidance_notes
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await clauses.setStandard( data.standard || null, {
            transaction,
        });
        

        

        

        return clauses;
    }
    

    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 clausesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                clause_code: item.clause_code
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                text_excerpt: item.text_excerpt
            ||
            null
            ,
            
                guidance_notes: item.guidance_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 clauses = await db.clauses.bulkCreate(clausesData, { transaction });

        // For each item created, replace relation files
        

        return clauses;
    }

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

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


        

        const updatePayload = {};
        
        if (data.clause_code !== undefined) updatePayload.clause_code = data.clause_code;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.text_excerpt !== undefined) updatePayload.text_excerpt = data.text_excerpt;
        
        
        if (data.guidance_notes !== undefined) updatePayload.guidance_notes = data.guidance_notes;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.standard !== undefined) {
            await clauses.setStandard(
              
              data.standard,
              
              { transaction }
            );
        }
        

        
        

        

        return clauses;
    }

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

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

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


        return clauses;
    }

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

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

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

        await clauses.destroy({
            transaction
        });

        return clauses;
    }

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

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

        if (!clauses) {
            return clauses;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.standard = await clauses.getStandard({
            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 = [

      {
        model: db.standards,
        as: 'standard',
        
        where: filter.standard ? {
          [Op.or]: [
            { id: { [Op.in]: filter.standard.split('|').map(term => Utils.uuid(term)) } },
            {
              short_name: {
                [Op.or]: filter.standard.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.clause_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clauses',
                        'clause_code',
                        filter.clause_code,
                    ),
                };
            }
            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clauses',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.text_excerpt) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clauses',
                        'text_excerpt',
                        filter.text_excerpt,
                    ),
                };
            }
            
            if (filter.guidance_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'clauses',
                        'guidance_notes',
                        filter.guidance_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.clauses.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(
                        'clauses',
                        'clause_code',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

