
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
            ,
            
        code: data.code
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        delivery_method: data.delivery_method
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        budget_amount: data.budget_amount
        ||
        null
            ,
            
        budget_currency: data.budget_currency
        ||
        null
            ,
            
        external_costs: data.external_costs
        ||
        null
            ,
            
        estimated_hours: data.estimated_hours
        ||
        null
            ,
            
        actual_hours: data.actual_hours
        ||
        null
            ,
            
        risk_level: data.risk_level
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await projects.setTenant( data.tenant || null, {
            transaction,
        });
        
        await projects.setCompany( data.company || null, {
            transaction,
        });
        
        await projects.setDeal( data.deal || null, {
            transaction,
        });
        
        await projects.setTemplate( data.template || null, {
            transaction,
        });
        
        await projects.setService_line( data.service_line || null, {
            transaction,
        });
        
        await projects.setProject_manager( data.project_manager || null, {
            transaction,
        });
        
        await projects.setOrganizations( data.organizations || null, {
            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
            ,
            
                code: item.code
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                delivery_method: item.delivery_method
            ||
            null
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
                budget_amount: item.budget_amount
            ||
            null
            ,
            
                budget_currency: item.budget_currency
            ||
            null
            ,
            
                external_costs: item.external_costs
            ||
            null
            ,
            
                estimated_hours: item.estimated_hours
            ||
            null
            ,
            
                actual_hours: item.actual_hours
            ||
            null
            ,
            
                risk_level: item.risk_level
            ||
            null
            ,
            
                summary: item.summary
            ||
            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.code !== undefined) updatePayload.code = data.code;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.delivery_method !== undefined) updatePayload.delivery_method = data.delivery_method;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.budget_amount !== undefined) updatePayload.budget_amount = data.budget_amount;
        
        
        if (data.budget_currency !== undefined) updatePayload.budget_currency = data.budget_currency;
        
        
        if (data.external_costs !== undefined) updatePayload.external_costs = data.external_costs;
        
        
        if (data.estimated_hours !== undefined) updatePayload.estimated_hours = data.estimated_hours;
        
        
        if (data.actual_hours !== undefined) updatePayload.actual_hours = data.actual_hours;
        
        
        if (data.risk_level !== undefined) updatePayload.risk_level = data.risk_level;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await projects.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.company !== undefined) {
            await projects.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.deal !== undefined) {
            await projects.setDeal(
              
              data.deal,
              
              { transaction }
            );
        }
        
        if (data.template !== undefined) {
            await projects.setTemplate(
              
              data.template,
              
              { transaction }
            );
        }
        
        if (data.service_line !== undefined) {
            await projects.setService_line(
              
              data.service_line,
              
              { transaction }
            );
        }
        
        if (data.project_manager !== undefined) {
            await projects.setProject_manager(
              
              data.project_manager,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await projects.setOrganizations(
              
              data.organizations,
              
              { 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,
        });

        if (projects.length !== ids.length) {
            const error = new Error('One or more items were not found in the current organization scope.');
            error.code = 404;
            throw error;
        }

        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);

        if (!projects) {
            const error = new Error('Item not found in the current organization scope.');
            error.code = 404;
            throw error;
        }

        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.milestones_project = await projects.getMilestones_project({
            transaction
        });
        
        
        output.tasks_project = await projects.getTasks_project({
            transaction
        });
        
        
        
        output.deliverables_project = await projects.getDeliverables_project({
            transaction
        });
        
        
        output.project_risks_project = await projects.getProject_risks_project({
            transaction
        });
        
        
        output.project_status_reports_project = await projects.getProject_status_reports_project({
            transaction
        });
        
        
        
        
        
        output.resource_allocations_project = await projects.getResource_allocations_project({
            transaction
        });
        
        
        
        
        
        output.time_entries_project = await projects.getTime_entries_project({
            transaction
        });
        
        
        
        
        output.invoices_project = await projects.getInvoices_project({
            transaction
        });
        
        
        
        
        
        output.support_tickets_project = await projects.getSupport_tickets_project({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.tenant = await projects.getTenant({
            transaction
        });
        
        
        output.company = await projects.getCompany({
            transaction
        });
        
        
        output.deal = await projects.getDeal({
            transaction
        });
        
        
        output.template = await projects.getTemplate({
            transaction
        });
        
        
        output.service_line = await projects.getService_line({
            transaction
        });
        
        
        output.project_manager = await projects.getProject_manager({
            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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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

      {
        model: db.users,
        as: 'project_manager',
        
        where: filter.project_manager ? {
          [Op.or]: [
            { id: { [Op.in]: filter.project_manager.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.project_manager.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.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'code',
                        filter.code,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'projects',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.delivery_method) {
                where = {
                    ...where,
                delivery_method: filter.delivery_method,
            };
            }
            
            if (filter.budget_currency) {
                where = {
                    ...where,
                budget_currency: filter.budget_currency,
            };
            }
            
            if (filter.risk_level) {
                where = {
                    ...where,
                risk_level: filter.risk_level,
            };
            }
            


      

      

      

      

      

      

      
      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.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.organizationsId = 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,
        }));
    }

    
};

