
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,
        
        document_number: data.document_number
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        document_type: data.document_type
        ||
        null
            ,
            
        revision: data.revision
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        effective_from: data.effective_from
        ||
        null
            ,
            
        effective_to: data.effective_to
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.documents.getTableName(),
                belongsToColumn: 'file',
                belongsToId: documents.id,
            },
            data.file,
            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,
                
                document_number: item.document_number
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                document_type: item.document_type
            ||
            null
            ,
            
                revision: item.revision
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                effective_from: item.effective_from
            ||
            null
            ,
            
                effective_to: item.effective_to
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
            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: 'file',
                    belongsToId: documents[i].id,
                },
                data[i].file,
                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.document_number !== undefined) updatePayload.document_number = data.document_number;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.document_type !== undefined) updatePayload.document_type = data.document_type;
        
        
        if (data.revision !== undefined) updatePayload.revision = data.revision;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.effective_from !== undefined) updatePayload.effective_from = data.effective_from;
        
        
        if (data.effective_to !== undefined) updatePayload.effective_to = data.effective_to;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.documents.getTableName(),
                belongsToColumn: 'file',
                belongsToId: documents.id,
            },
            data.file,
            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.owner = await documents.getOwner({
            transaction
        });
        
        
        output.file = await documents.getFile({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

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

            
            

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

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

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

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

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

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

            
            if (filter.document_type) {
                where = {
                    ...where,
                document_type: filter.document_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.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,
        }));
    }

    
};

