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

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

        const documents = await db.documents.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        document_number: data.document_number
        ||
        null
            ,
            
        current_revision: data.current_revision
        ||
        null
            ,
            
        lifecycle_status: data.lifecycle_status
        ||
        null
            ,
            
        control_level: data.control_level
        ||
        null
            ,
            
        confidentiality: data.confidentiality
        ||
        null
            ,
            
        effective_date: data.effective_date
        ||
        null
            ,
            
        next_review_date: data.next_review_date
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        content: data.content
        ||
        null
            ,
            
        training_required: data.training_required
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await documents.setDocument_type( data.document_type || null, {
            transaction,
        });
        
        await documents.setTemplate( data.template || null, {
            transaction,
        });
        
        await documents.setOwner( data.owner || null, {
            transaction,
        });
        
        await documents.setApprover( data.approver || null, {
            transaction,
        });
        

        
        await documents.setMapped_clauses(data.mapped_clauses || [], {
            transaction,
        });
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.documents.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: documents.id,
            },
            data.attachments,
            options,
        );
        

        return documents;
    }
    

    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 documentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                document_number: item.document_number
            ||
            null
            ,
            
                current_revision: item.current_revision
            ||
            null
            ,
            
                lifecycle_status: item.lifecycle_status
            ||
            null
            ,
            
                control_level: item.control_level
            ||
            null
            ,
            
                confidentiality: item.confidentiality
            ||
            null
            ,
            
                effective_date: item.effective_date
            ||
            null
            ,
            
                next_review_date: item.next_review_date
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                content: item.content
            ||
            null
            ,
            
                training_required: item.training_required
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < documents.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.documents.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: documents[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        return documents;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.document_number !== undefined) updatePayload.document_number = data.document_number;
        
        
        if (data.current_revision !== undefined) updatePayload.current_revision = data.current_revision;
        
        
        if (data.lifecycle_status !== undefined) updatePayload.lifecycle_status = data.lifecycle_status;
        
        
        if (data.control_level !== undefined) updatePayload.control_level = data.control_level;
        
        
        if (data.confidentiality !== undefined) updatePayload.confidentiality = data.confidentiality;
        
        
        if (data.effective_date !== undefined) updatePayload.effective_date = data.effective_date;
        
        
        if (data.next_review_date !== undefined) updatePayload.next_review_date = data.next_review_date;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.content !== undefined) updatePayload.content = data.content;
        
        
        if (data.training_required !== undefined) updatePayload.training_required = data.training_required;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.document_type !== undefined) {
            await documents.setDocument_type(
              
              data.document_type,
              
              { transaction }
            );
        }
        
        if (data.template !== undefined) {
            await documents.setTemplate(
              
              data.template,
              
              { transaction }
            );
        }
        
        if (data.owner !== undefined) {
            await documents.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        
        if (data.approver !== undefined) {
            await documents.setApprover(
              
              data.approver,
              
              { transaction }
            );
        }
        

        
        
        if (data.mapped_clauses !== undefined) {
            await documents.setMapped_clauses(data.mapped_clauses, { transaction });
        }
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.documents.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: documents.id,
            },
            data.attachments,
            options,
        );
        

        return documents;
    }

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

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

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


        return documents;
    }

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

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

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

        await documents.destroy({
            transaction
        });

        return documents;
    }

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

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

        if (!documents) {
            return documents;
        }

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

        
        
        
        
        
        
        
        
        
        output.document_versions_document = await documents.getDocument_versions_document({
            transaction
        });
        
        
        output.change_requests_document = await documents.getChange_requests_document({
            transaction
        });
        
        
        
        
        
        
        
        output.training_assignments_document = await documents.getTraining_assignments_document({
            transaction
        });
        
        
        
        
        output.batches_bmr_document = await documents.getBatches_bmr_document({
            transaction
        });
        
        
        
        
        
        
        output.capas_related_document = await documents.getCapas_related_document({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.document_type = await documents.getDocument_type({
            transaction
        });
        
        
        output.template = await documents.getTemplate({
            transaction
        });
        
        
        output.owner = await documents.getOwner({
            transaction
        });
        
        
        output.approver = await documents.getApprover({
            transaction
        });
        
        
        output.attachments = await documents.getAttachments({
            transaction
        });
        
        
        output.mapped_clauses = await documents.getMapped_clauses({
            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.document_types,
        as: 'document_type',
        
        where: filter.document_type ? {
          [Op.or]: [
            { id: { [Op.in]: filter.document_type.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.document_type.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        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}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.clauses,
        as: 'mapped_clauses',
        required: false,
      },


      {
        model: db.file,
        as: 'attachments',
      },

    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'documents',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.document_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'documents',
                        'document_number',
                        filter.document_number,
                    ),
                };
            }
            
            if (filter.current_revision) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'documents',
                        'current_revision',
                        filter.current_revision,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'documents',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            
            if (filter.content) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'documents',
                        'content',
                        filter.content,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.lifecycle_status) {
                where = {
                    ...where,
                lifecycle_status: filter.lifecycle_status,
            };
            }
            
            if (filter.control_level) {
                where = {
                    ...where,
                control_level: filter.control_level,
            };
            }
            
            if (filter.confidentiality) {
                where = {
                    ...where,
                confidentiality: filter.confidentiality,
            };
            }
            
            if (filter.training_required) {
                where = {
                    ...where,
                training_required: filter.training_required,
            };
            }
            


      

      

      

      


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

        include = [
          {
            model: db.clauses,
            as: 'mapped_clauses_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  clause_code: {
                    [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.documents.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(
                        'documents',
                        'title',
                        query,
                    ),
                ],
            };
        }

        const records = await db.documents.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,
        }));
    }

    
};

