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

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

        const business_plan_versions = await db.business_plan_versions.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        audience: data.audience
        ||
        null
            ,
            
        stage: data.stage
        ||
        null
            ,
            
        executive_summary: data.executive_summary
        ||
        null
            ,
            
        full_plan: data.full_plan
        ||
        null
            ,
            
        assumptions: data.assumptions
        ||
        null
            ,
            
        generated_at: data.generated_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await business_plan_versions.setProject( data.project || null, {
            transaction,
        });
        
        await business_plan_versions.setGenerated_by_run( data.generated_by_run || null, {
            transaction,
        });
        
        await business_plan_versions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return business_plan_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 business_plan_versionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                audience: item.audience
            ||
            null
            ,
            
                stage: item.stage
            ||
            null
            ,
            
                executive_summary: item.executive_summary
            ||
            null
            ,
            
                full_plan: item.full_plan
            ||
            null
            ,
            
                assumptions: item.assumptions
            ||
            null
            ,
            
                generated_at: item.generated_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return business_plan_versions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.audience !== undefined) updatePayload.audience = data.audience;
        
        
        if (data.stage !== undefined) updatePayload.stage = data.stage;
        
        
        if (data.executive_summary !== undefined) updatePayload.executive_summary = data.executive_summary;
        
        
        if (data.full_plan !== undefined) updatePayload.full_plan = data.full_plan;
        
        
        if (data.assumptions !== undefined) updatePayload.assumptions = data.assumptions;
        
        
        if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await business_plan_versions.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.generated_by_run !== undefined) {
            await business_plan_versions.setGenerated_by_run(
              
              data.generated_by_run,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await business_plan_versions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return business_plan_versions;
    }

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

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

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


        return business_plan_versions;
    }

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

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

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

        await business_plan_versions.destroy({
            transaction
        });

        return business_plan_versions;
    }

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

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

        if (!business_plan_versions) {
            return business_plan_versions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.project = await business_plan_versions.getProject({
            transaction
        });
        
        
        output.exports = await business_plan_versions.getExports({
            transaction
        });
        
        
        output.generated_by_run = await business_plan_versions.getGenerated_by_run({
            transaction
        });
        
        
        output.organizations = await business_plan_versions.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



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

    ];

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

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

            
            

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

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

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

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

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


      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.business_plan_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'business_plan_versions',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

    
};

