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

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

        const project_phases = await db.project_phases.create(
            {
                id: data.id || undefined,
        
        phase_type: data.phase_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        start_date: data.start_date
        ||
        null
            ,
            
        target_date: data.target_date
        ||
        null
            ,
            
        approved_at: data.approved_at
        ||
        null
            ,
            
        gate_notes: data.gate_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await project_phases.setProject( data.project || null, {
            transaction,
        });
        
        await project_phases.setApproved_by( data.approved_by || null, {
            transaction,
        });
        
        await project_phases.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return project_phases;
    }
    

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

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

        // For each item created, replace relation files
        

        return project_phases;
    }

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


        

        const updatePayload = {};
        
        if (data.phase_type !== undefined) updatePayload.phase_type = data.phase_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.start_date !== undefined) updatePayload.start_date = data.start_date;
        
        
        if (data.target_date !== undefined) updatePayload.target_date = data.target_date;
        
        
        if (data.approved_at !== undefined) updatePayload.approved_at = data.approved_at;
        
        
        if (data.gate_notes !== undefined) updatePayload.gate_notes = data.gate_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await project_phases.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.approved_by !== undefined) {
            await project_phases.setApproved_by(
              
              data.approved_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await project_phases.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return project_phases;
    }

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

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

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


        return project_phases;
    }

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

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

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

        await project_phases.destroy({
            transaction
        });

        return project_phases;
    }

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

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

        if (!project_phases) {
            return project_phases;
        }

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

        
        
        
        
        
        
        
        output.milestones_phase = await project_phases.getMilestones_phase({
            transaction
        });
        
        
        
        
        
        
        
        output.metallurgical_tests_phase = await project_phases.getMetallurgical_tests_phase({
            transaction
        });
        
        
        
        output.flowsheets_phase = await project_phases.getFlowsheets_phase({
            transaction
        });
        
        
        
        
        
        output.design_criteria_items_phase = await project_phases.getDesign_criteria_items_phase({
            transaction
        });
        
        
        output.economic_models_phase = await project_phases.getEconomic_models_phase({
            transaction
        });
        
        
        
        
        
        output.documents_phase = await project_phases.getDocuments_phase({
            transaction
        });
        
        
        
        
        output.tasks_phase = await project_phases.getTasks_phase({
            transaction
        });
        
        
        
        
        
        
        
        output.project = await project_phases.getProject({
            transaction
        });
        
        
        output.approved_by = await project_phases.getApproved_by({
            transaction
        });
        
        
        output.organizations = await project_phases.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.users,
        as: 'approved_by',
        
        where: filter.approved_by ? {
          [Op.or]: [
            { id: { [Op.in]: filter.approved_by.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.approved_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    start_date: {
                    ...where.start_date,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.target_dateRange) {
                const [start, end] = filter.target_dateRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    target_date: {
                    ...where.target_date,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.approved_atRange) {
                const [start, end] = filter.approved_atRange;

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

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

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

            
            if (filter.phase_type) {
                where = {
                    ...where,
                phase_type: filter.phase_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.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.project_phases.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(
                        'project_phases',
                        'gate_notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

