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

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

        const waiver_documents = await db.waiver_documents.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        document_type: data.document_type
        ||
        null
            ,
            
        is_required: data.is_required
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await waiver_documents.setCamp_session( data.camp_session || null, {
            transaction,
        });
        

        

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

        return waiver_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 waiver_documentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                document_type: item.document_type
            ||
            null
            ,
            
                is_required: item.is_required
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return waiver_documents;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.document_type !== undefined) updatePayload.document_type = data.document_type;
        
        
        if (data.is_required !== undefined) updatePayload.is_required = data.is_required;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.camp_session !== undefined) {
            await waiver_documents.setCamp_session(
              
              data.camp_session,
              
              { transaction }
            );
        }
        

        
        

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

        return waiver_documents;
    }

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

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

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


        return waiver_documents;
    }

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

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

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

        await waiver_documents.destroy({
            transaction
        });

        return waiver_documents;
    }

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

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

        if (!waiver_documents) {
            return waiver_documents;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.document_signatures_waiver_document = await waiver_documents.getDocument_signatures_waiver_document({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.document_file = await waiver_documents.getDocument_file({
            transaction
        });
        
        
        output.camp_session = await waiver_documents.getCamp_session({
            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.camp_sessions,
        as: 'camp_session',
        
        where: filter.camp_session ? {
          [Op.or]: [
            { id: { [Op.in]: filter.camp_session.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.camp_session.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

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

            
            

            

            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.is_required) {
                where = {
                    ...where,
                is_required: filter.is_required,
            };
            }
            


      



            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.waiver_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(
                        'waiver_documents',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

    
};

