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

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

        const advance_directives = await db.advance_directives.create(
            {
                id: data.id || undefined,
        
        directive_type: data.directive_type
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        proxy_contact_details: data.proxy_contact_details
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await advance_directives.setUser( data.user || null, {
            transaction,
        });
        

        

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

        return advance_directives;
    }
    

    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 advance_directivesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                directive_type: item.directive_type
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                proxy_contact_details: item.proxy_contact_details
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return advance_directives;
    }

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

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


        

        const updatePayload = {};
        
        if (data.directive_type !== undefined) updatePayload.directive_type = data.directive_type;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.proxy_contact_details !== undefined) updatePayload.proxy_contact_details = data.proxy_contact_details;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await advance_directives.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

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

        return advance_directives;
    }

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

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

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


        return advance_directives;
    }

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

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

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

        await advance_directives.destroy({
            transaction
        });

        return advance_directives;
    }

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

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

        if (!advance_directives) {
            return advance_directives;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await advance_directives.getUser({
            transaction
        });
        
        
        output.document_files = await advance_directives.getDocument_files({
            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: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'advance_directives',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            
            if (filter.proxy_contact_details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'advance_directives',
                        'proxy_contact_details',
                        filter.proxy_contact_details,
                    ),
                };
            }
            

            
            

            

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

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


      



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

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

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

    
};

