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

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

        const deliverables = await db.deliverables.create(
            {
                id: data.id || undefined,
        
        message: data.message
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        review_status: data.review_status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await deliverables.setContract( data.contract || null, {
            transaction,
        });
        
        await deliverables.setMilestone( data.milestone || null, {
            transaction,
        });
        
        await deliverables.setSubmitted_by( data.submitted_by || null, {
            transaction,
        });
        

        

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

        return deliverables;
    }
    

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

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

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

        return deliverables;
    }

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

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


        

        const updatePayload = {};
        
        if (data.message !== undefined) updatePayload.message = data.message;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.review_status !== undefined) updatePayload.review_status = data.review_status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.contract !== undefined) {
            await deliverables.setContract(
              
              data.contract,
              
              { transaction }
            );
        }
        
        if (data.milestone !== undefined) {
            await deliverables.setMilestone(
              
              data.milestone,
              
              { transaction }
            );
        }
        
        if (data.submitted_by !== undefined) {
            await deliverables.setSubmitted_by(
              
              data.submitted_by,
              
              { transaction }
            );
        }
        

        
        

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

        return deliverables;
    }

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

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

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


        return deliverables;
    }

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

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

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

        await deliverables.destroy({
            transaction
        });

        return deliverables;
    }

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

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

        if (!deliverables) {
            return deliverables;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.contract = await deliverables.getContract({
            transaction
        });
        
        
        output.milestone = await deliverables.getMilestone({
            transaction
        });
        
        
        output.submitted_by = await deliverables.getSubmitted_by({
            transaction
        });
        
        
        output.files = await deliverables.getFiles({
            transaction
        });
        
        
        output.images = await deliverables.getImages({
            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.contracts,
        as: 'contract',
        
        where: filter.contract ? {
          [Op.or]: [
            { id: { [Op.in]: filter.contract.split('|').map(term => Utils.uuid(term)) } },
            {
              terms: {
                [Op.or]: filter.contract.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

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

    ];

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

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

            
            

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

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

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

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

            
            if (filter.review_status) {
                where = {
                    ...where,
                review_status: filter.review_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.deliverables.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(
                        'deliverables',
                        'message',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

