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

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

        const projects = await db.projects.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        project_type: data.project_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        industry: data.industry
        ||
        null
            ,
            
        target_market: data.target_market
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await projects.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await projects.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await projects.setSource_items(data.source_items || [], {
            transaction,
        });
        
        await projects.setMind_maps(data.mind_maps || [], {
            transaction,
        });
        
        await projects.setAi_runs(data.ai_runs || [], {
            transaction,
        });
        
        await projects.setBusiness_plan_versions(data.business_plan_versions || [], {
            transaction,
        });
        
        await projects.setDeal_packages(data.deal_packages || [], {
            transaction,
        });
        

        

        return projects;
    }
    

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

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

        // For each item created, replace relation files
        

        return projects;
    }

    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 projects = await db.projects.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.project_type !== undefined) updatePayload.project_type = data.project_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.industry !== undefined) updatePayload.industry = data.industry;
        
        
        if (data.target_market !== undefined) updatePayload.target_market = data.target_market;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workspace !== undefined) {
            await projects.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await projects.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.source_items !== undefined) {
            await projects.setSource_items(data.source_items, { transaction });
        }
        
        if (data.mind_maps !== undefined) {
            await projects.setMind_maps(data.mind_maps, { transaction });
        }
        
        if (data.ai_runs !== undefined) {
            await projects.setAi_runs(data.ai_runs, { transaction });
        }
        
        if (data.business_plan_versions !== undefined) {
            await projects.setBusiness_plan_versions(data.business_plan_versions, { transaction });
        }
        
        if (data.deal_packages !== undefined) {
            await projects.setDeal_packages(data.deal_packages, { transaction });
        }
        

        

        return projects;
    }

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

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

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


        return projects;
    }

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

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

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

        await projects.destroy({
            transaction
        });

        return projects;
    }

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

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

        if (!projects) {
            return projects;
        }

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

        
        
        
        
        
        
        
        
        output.mind_maps_project = await projects.getMind_maps_project({
            transaction
        });
        
        
        
        
        output.source_items_project = await projects.getSource_items_project({
            transaction
        });
        
        
        
        output.ai_runs_project = await projects.getAi_runs_project({
            transaction
        });
        
        
        output.business_plan_versions_project = await projects.getBusiness_plan_versions_project({
            transaction
        });
        
        
        output.pitch_decks_project = await projects.getPitch_decks_project({
            transaction
        });
        
        
        output.deal_packages_project = await projects.getDeal_packages_project({
            transaction
        });
        
        
        
        output.tasks_project = await projects.getTasks_project({
            transaction
        });
        
        
        
        output.workspace = await projects.getWorkspace({
            transaction
        });
        
        
        output.source_items = await projects.getSource_items({
            transaction
        });
        
        
        output.mind_maps = await projects.getMind_maps({
            transaction
        });
        
        
        output.ai_runs = await projects.getAi_runs({
            transaction
        });
        
        
        output.business_plan_versions = await projects.getBusiness_plan_versions({
            transaction
        });
        
        
        output.deal_packages = await projects.getDeal_packages({
            transaction
        });
        
        
        output.organizations = await projects.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.workspaces,
        as: 'workspace',
        
        where: filter.workspace ? {
          [Op.or]: [
            { id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.source_items,
        as: 'source_items',
        required: false,
      },

      {
        model: db.mind_maps,
        as: 'mind_maps',
        required: false,
      },

      {
        model: db.ai_runs,
        as: 'ai_runs',
        required: false,
      },

      {
        model: db.business_plan_versions,
        as: 'business_plan_versions',
        required: false,
      },

      {
        model: db.deal_packages,
        as: 'deal_packages',
        required: false,
      },


    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            
            if (filter.industry) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'industry',
                        filter.industry,
                    ),
                };
            }
            
            if (filter.target_market) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'target_market',
                        filter.target_market,
                    ),
                };
            }
            

            
            

            

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

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


      

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

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


      if (filter.source_items) {
        const searchTerms = filter.source_items.split('|');

        include = [
          {
            model: db.source_items,
            as: 'source_items_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  title: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.mind_maps) {
        const searchTerms = filter.mind_maps.split('|');

        include = [
          {
            model: db.mind_maps,
            as: 'mind_maps_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.ai_runs) {
        const searchTerms = filter.ai_runs.split('|');

        include = [
          {
            model: db.ai_runs,
            as: 'ai_runs_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  run_type: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.business_plan_versions) {
        const searchTerms = filter.business_plan_versions.split('|');

        include = [
          {
            model: db.business_plan_versions,
            as: 'business_plan_versions_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  title: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.deal_packages) {
        const searchTerms = filter.deal_packages.split('|');

        include = [
          {
            model: db.deal_packages,
            as: 'deal_packages_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  title: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

