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

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

        const document_versions = await db.document_versions.create(
            {
                id: data.id || undefined,
        
        version_no: data.version_no
        ||
        null
            ,
            
        number: data.number
        ||
        null
            ,
            
        issued_at: data.issued_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        country: data.country
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        is_current: data.is_current
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await document_versions.setDocument( data.document || null, {
            transaction,
        });
        

        

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

        return document_versions;
    }
    

    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 document_versionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                version_no: item.version_no
            ||
            null
            ,
            
                number: item.number
            ||
            null
            ,
            
                issued_at: item.issued_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                country: item.country
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                is_current: item.is_current
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return document_versions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.version_no !== undefined) updatePayload.version_no = data.version_no;
        
        
        if (data.number !== undefined) updatePayload.number = data.number;
        
        
        if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.country !== undefined) updatePayload.country = data.country;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.is_current !== undefined) updatePayload.is_current = data.is_current;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.document !== undefined) {
            await document_versions.setDocument(
              
              data.document,
              
              { transaction }
            );
        }
        

        
        

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

        return document_versions;
    }

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

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

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


        return document_versions;
    }

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

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

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

        await document_versions.destroy({
            transaction
        });

        return document_versions;
    }

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

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

        if (!document_versions) {
            return document_versions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.documents_current_version = await document_versions.getDocuments_current_version({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.document = await document_versions.getDocument({
            transaction
        });
        
        
        output.files = await document_versions.getFiles({
            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.documents,
        as: 'document',
        
        where: filter.document ? {
          [Op.or]: [
            { id: { [Op.in]: filter.document.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.document.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_versions',
                        'number',
                        filter.number,
                    ),
                };
            }
            
            if (filter.country) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_versions',
                        'country',
                        filter.country,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_versions',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};

