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

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

        const citator_checks = await db.citator_checks.create(
            {
                id: data.id || undefined,
        
        standing: data.standing
        ||
        null
            ,
            
        analysis: data.analysis
        ||
        null
            ,
            
        conflicts_summary: data.conflicts_summary
        ||
        null
            ,
            
        checked_at: data.checked_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await citator_checks.setRequested_by( data.requested_by || null, {
            transaction,
        });
        
        await citator_checks.setMatter( data.matter || null, {
            transaction,
        });
        
        await citator_checks.setLegal_source( data.legal_source || null, {
            transaction,
        });
        

        

        

        return citator_checks;
    }
    

    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 citator_checksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                standing: item.standing
            ||
            null
            ,
            
                analysis: item.analysis
            ||
            null
            ,
            
                conflicts_summary: item.conflicts_summary
            ||
            null
            ,
            
                checked_at: item.checked_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return citator_checks;
    }

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

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


        

        const updatePayload = {};
        
        if (data.standing !== undefined) updatePayload.standing = data.standing;
        
        
        if (data.analysis !== undefined) updatePayload.analysis = data.analysis;
        
        
        if (data.conflicts_summary !== undefined) updatePayload.conflicts_summary = data.conflicts_summary;
        
        
        if (data.checked_at !== undefined) updatePayload.checked_at = data.checked_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.requested_by !== undefined) {
            await citator_checks.setRequested_by(
              
              data.requested_by,
              
              { transaction }
            );
        }
        
        if (data.matter !== undefined) {
            await citator_checks.setMatter(
              
              data.matter,
              
              { transaction }
            );
        }
        
        if (data.legal_source !== undefined) {
            await citator_checks.setLegal_source(
              
              data.legal_source,
              
              { transaction }
            );
        }
        

        
        

        

        return citator_checks;
    }

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

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

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


        return citator_checks;
    }

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

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

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

        await citator_checks.destroy({
            transaction
        });

        return citator_checks;
    }

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

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

        if (!citator_checks) {
            return citator_checks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.requested_by = await citator_checks.getRequested_by({
            transaction
        });
        
        
        output.matter = await citator_checks.getMatter({
            transaction
        });
        
        
        output.legal_source = await citator_checks.getLegal_source({
            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.users,
        as: 'requested_by',
        
        where: filter.requested_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.requested_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.requested_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.analysis) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'citator_checks',
                        'analysis',
                        filter.analysis,
                    ),
                };
            }
            
            if (filter.conflicts_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'citator_checks',
                        'conflicts_summary',
                        filter.conflicts_summary,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      

      



            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.citator_checks.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(
                        'citator_checks',
                        'standing',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

