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

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

        const document_signatures = await db.document_signatures.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        signed_datetime: data.signed_datetime
        ||
        null
            ,
            
        signature_name: data.signature_name
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await document_signatures.setWaiver_document( data.waiver_document || null, {
            transaction,
        });
        
        await document_signatures.setEnrollment( data.enrollment || null, {
            transaction,
        });
        
        await document_signatures.setGuardian( data.guardian || null, {
            transaction,
        });
        

        

        

        return document_signatures;
    }
    

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

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

        // For each item created, replace relation files
        

        return document_signatures;
    }

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

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.signed_datetime !== undefined) updatePayload.signed_datetime = data.signed_datetime;
        
        
        if (data.signature_name !== undefined) updatePayload.signature_name = data.signature_name;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.waiver_document !== undefined) {
            await document_signatures.setWaiver_document(
              
              data.waiver_document,
              
              { transaction }
            );
        }
        
        if (data.enrollment !== undefined) {
            await document_signatures.setEnrollment(
              
              data.enrollment,
              
              { transaction }
            );
        }
        
        if (data.guardian !== undefined) {
            await document_signatures.setGuardian(
              
              data.guardian,
              
              { transaction }
            );
        }
        

        
        

        

        return document_signatures;
    }

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

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

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


        return document_signatures;
    }

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

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

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

        await document_signatures.destroy({
            transaction
        });

        return document_signatures;
    }

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

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

        if (!document_signatures) {
            return document_signatures;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.waiver_document = await document_signatures.getWaiver_document({
            transaction
        });
        
        
        output.enrollment = await document_signatures.getEnrollment({
            transaction
        });
        
        
        output.guardian = await document_signatures.getGuardian({
            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.waiver_documents,
        as: 'waiver_document',
        
        where: filter.waiver_document ? {
          [Op.or]: [
            { id: { [Op.in]: filter.waiver_document.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.waiver_document.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.signature_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_signatures',
                        'signature_name',
                        filter.signature_name,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            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.document_signatures.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_signatures',
                        'signature_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

