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

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

        const matters = await db.matters.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        matter_type: data.matter_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        jurisdiction: data.jurisdiction
        ||
        null
            ,
            
        court_name: data.court_name
        ||
        null
            ,
            
        case_number: data.case_number
        ||
        null
            ,
            
        filed_at: data.filed_at
        ||
        null
            ,
            
        next_hearing_at: data.next_hearing_at
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await matters.setOwner( data.owner || null, {
            transaction,
        });
        

        

        

        return matters;
    }
    

    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 mattersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                matter_type: item.matter_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                jurisdiction: item.jurisdiction
            ||
            null
            ,
            
                court_name: item.court_name
            ||
            null
            ,
            
                case_number: item.case_number
            ||
            null
            ,
            
                filed_at: item.filed_at
            ||
            null
            ,
            
                next_hearing_at: item.next_hearing_at
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return matters;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.matter_type !== undefined) updatePayload.matter_type = data.matter_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.jurisdiction !== undefined) updatePayload.jurisdiction = data.jurisdiction;
        
        
        if (data.court_name !== undefined) updatePayload.court_name = data.court_name;
        
        
        if (data.case_number !== undefined) updatePayload.case_number = data.case_number;
        
        
        if (data.filed_at !== undefined) updatePayload.filed_at = data.filed_at;
        
        
        if (data.next_hearing_at !== undefined) updatePayload.next_hearing_at = data.next_hearing_at;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner !== undefined) {
            await matters.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        

        
        

        

        return matters;
    }

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

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

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


        return matters;
    }

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

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

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

        await matters.destroy({
            transaction
        });

        return matters;
    }

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

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

        if (!matters) {
            return matters;
        }

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

        
        
        
        
        
        
        
        output.matter_parties_matter = await matters.getMatter_parties_matter({
            transaction
        });
        
        
        output.files_matter = await matters.getFiles_matter({
            transaction
        });
        
        
        
        output.assistant_threads_matter = await matters.getAssistant_threads_matter({
            transaction
        });
        
        
        
        output.ai_jobs_matter = await matters.getAi_jobs_matter({
            transaction
        });
        
        
        
        
        output.generated_documents_matter = await matters.getGenerated_documents_matter({
            transaction
        });
        
        
        
        output.research_queries_matter = await matters.getResearch_queries_matter({
            transaction
        });
        
        
        
        
        output.citator_checks_matter = await matters.getCitator_checks_matter({
            transaction
        });
        
        
        output.mock_trials_matter = await matters.getMock_trials_matter({
            transaction
        });
        
        
        
        
        output.transcription_jobs_matter = await matters.getTranscription_jobs_matter({
            transaction
        });
        
        
        output.medical_chronology_reports_matter = await matters.getMedical_chronology_reports_matter({
            transaction
        });
        
        
        
        output.causation_analyses_matter = await matters.getCausation_analyses_matter({
            transaction
        });
        
        
        output.audit_events_matter = await matters.getAudit_events_matter({
            transaction
        });
        
        
        
        output.owner = await matters.getOwner({
            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: 'owner',
        
        where: filter.owner ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'matters',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.jurisdiction) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'matters',
                        'jurisdiction',
                        filter.jurisdiction,
                    ),
                };
            }
            
            if (filter.court_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'matters',
                        'court_name',
                        filter.court_name,
                    ),
                };
            }
            
            if (filter.case_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'matters',
                        'case_number',
                        filter.case_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'matters',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    filed_at: {
                    ...where.filed_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.next_hearing_atRange) {
                const [start, end] = filter.next_hearing_atRange;

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

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

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

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


      



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

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

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

    
};

