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

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

        const causation_analyses = await db.causation_analyses.create(
            {
                id: data.id || undefined,
        
        analysis_title: data.analysis_title
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        theory_of_causation: data.theory_of_causation
        ||
        null
            ,
            
        supporting_facts: data.supporting_facts
        ||
        null
            ,
            
        weaknesses_and_gaps: data.weaknesses_and_gaps
        ||
        null
            ,
            
        generated_at: data.generated_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await causation_analyses.setRequested_by( data.requested_by || null, {
            transaction,
        });
        
        await causation_analyses.setMatter( data.matter || null, {
            transaction,
        });
        
        await causation_analyses.setExport_file( data.export_file || null, {
            transaction,
        });
        

        
        await causation_analyses.setSource_files(data.source_files || [], {
            transaction,
        });
        

        

        return causation_analyses;
    }
    

    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 causation_analysesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                analysis_title: item.analysis_title
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                theory_of_causation: item.theory_of_causation
            ||
            null
            ,
            
                supporting_facts: item.supporting_facts
            ||
            null
            ,
            
                weaknesses_and_gaps: item.weaknesses_and_gaps
            ||
            null
            ,
            
                generated_at: item.generated_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return causation_analyses;
    }

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

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


        

        const updatePayload = {};
        
        if (data.analysis_title !== undefined) updatePayload.analysis_title = data.analysis_title;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.theory_of_causation !== undefined) updatePayload.theory_of_causation = data.theory_of_causation;
        
        
        if (data.supporting_facts !== undefined) updatePayload.supporting_facts = data.supporting_facts;
        
        
        if (data.weaknesses_and_gaps !== undefined) updatePayload.weaknesses_and_gaps = data.weaknesses_and_gaps;
        
        
        if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.requested_by !== undefined) {
            await causation_analyses.setRequested_by(
              
              data.requested_by,
              
              { transaction }
            );
        }
        
        if (data.matter !== undefined) {
            await causation_analyses.setMatter(
              
              data.matter,
              
              { transaction }
            );
        }
        
        if (data.export_file !== undefined) {
            await causation_analyses.setExport_file(
              
              data.export_file,
              
              { transaction }
            );
        }
        

        
        
        if (data.source_files !== undefined) {
            await causation_analyses.setSource_files(data.source_files, { transaction });
        }
        

        

        return causation_analyses;
    }

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

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

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


        return causation_analyses;
    }

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

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

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

        await causation_analyses.destroy({
            transaction
        });

        return causation_analyses;
    }

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

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

        if (!causation_analyses) {
            return causation_analyses;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.requested_by = await causation_analyses.getRequested_by({
            transaction
        });
        
        
        output.matter = await causation_analyses.getMatter({
            transaction
        });
        
        
        output.source_files = await causation_analyses.getSource_files({
            transaction
        });
        
        
        output.export_file = await causation_analyses.getExport_file({
            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.files,
        as: 'export_file',
        
        where: filter.export_file ? {
          [Op.or]: [
            { id: { [Op.in]: filter.export_file.split('|').map(term => Utils.uuid(term)) } },
            {
              file_name: {
                [Op.or]: filter.export_file.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },


      {
        model: db.files,
        as: 'source_files',
        required: false,
      },


    ];

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

            
            if (filter.analysis_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'causation_analyses',
                        'analysis_title',
                        filter.analysis_title,
                    ),
                };
            }
            
            if (filter.theory_of_causation) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'causation_analyses',
                        'theory_of_causation',
                        filter.theory_of_causation,
                    ),
                };
            }
            
            if (filter.supporting_facts) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'causation_analyses',
                        'supporting_facts',
                        filter.supporting_facts,
                    ),
                };
            }
            
            if (filter.weaknesses_and_gaps) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'causation_analyses',
                        'weaknesses_and_gaps',
                        filter.weaknesses_and_gaps,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      

      


      if (filter.source_files) {
        const searchTerms = filter.source_files.split('|');

        include = [
          {
            model: db.files,
            as: 'source_files_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  file_name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

