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

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

        const services = await db.services.create(
            {
                id: data.id || undefined,
        
        name_fr: data.name_fr
        ||
        null
            ,
            
        name_en: data.name_en
        ||
        null
            ,
            
        description_fr: data.description_fr
        ||
        null
            ,
            
        description_en: data.description_en
        ||
        null
            ,
            
        deliverables: data.deliverables
        ||
        null
            ,
            
        pricing_model: data.pricing_model
        ||
        null
            ,
            
        min_price: data.min_price
        ||
        null
            ,
            
        max_price: data.max_price
        ||
        null
            ,
            
        typical_duration_weeks: data.typical_duration_weeks
        ||
        null
            ,
            
        required_skills: data.required_skills
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await services.setTenant( data.tenant || null, {
            transaction,
        });
        
        await services.setService_line( data.service_line || null, {
            transaction,
        });
        
        await services.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return services;
    }
    

    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 servicesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name_fr: item.name_fr
            ||
            null
            ,
            
                name_en: item.name_en
            ||
            null
            ,
            
                description_fr: item.description_fr
            ||
            null
            ,
            
                description_en: item.description_en
            ||
            null
            ,
            
                deliverables: item.deliverables
            ||
            null
            ,
            
                pricing_model: item.pricing_model
            ||
            null
            ,
            
                min_price: item.min_price
            ||
            null
            ,
            
                max_price: item.max_price
            ||
            null
            ,
            
                typical_duration_weeks: item.typical_duration_weeks
            ||
            null
            ,
            
                required_skills: item.required_skills
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return services;
    }

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


        

        const updatePayload = {};
        
        if (data.name_fr !== undefined) updatePayload.name_fr = data.name_fr;
        
        
        if (data.name_en !== undefined) updatePayload.name_en = data.name_en;
        
        
        if (data.description_fr !== undefined) updatePayload.description_fr = data.description_fr;
        
        
        if (data.description_en !== undefined) updatePayload.description_en = data.description_en;
        
        
        if (data.deliverables !== undefined) updatePayload.deliverables = data.deliverables;
        
        
        if (data.pricing_model !== undefined) updatePayload.pricing_model = data.pricing_model;
        
        
        if (data.min_price !== undefined) updatePayload.min_price = data.min_price;
        
        
        if (data.max_price !== undefined) updatePayload.max_price = data.max_price;
        
        
        if (data.typical_duration_weeks !== undefined) updatePayload.typical_duration_weeks = data.typical_duration_weeks;
        
        
        if (data.required_skills !== undefined) updatePayload.required_skills = data.required_skills;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await services.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.service_line !== undefined) {
            await services.setService_line(
              
              data.service_line,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await services.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return services;
    }

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

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

        if (services.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 services) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of services) {
                await record.destroy({transaction});
            }
        });


        return services;
    }

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

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

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

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

        await services.destroy({
            transaction
        });

        return services;
    }

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

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

        if (!services) {
            return services;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.leads_service_interest = await services.getLeads_service_interest({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await services.getTenant({
            transaction
        });
        
        
        output.service_line = await services.getService_line({
            transaction
        });
        
        
        output.organizations = await services.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.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.name_fr) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'services',
                        'name_fr',
                        filter.name_fr,
                    ),
                };
            }
            
            if (filter.name_en) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'services',
                        'name_en',
                        filter.name_en,
                    ),
                };
            }
            
            if (filter.description_fr) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'services',
                        'description_fr',
                        filter.description_fr,
                    ),
                };
            }
            
            if (filter.description_en) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'services',
                        'description_en',
                        filter.description_en,
                    ),
                };
            }
            
            if (filter.deliverables) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'services',
                        'deliverables',
                        filter.deliverables,
                    ),
                };
            }
            
            if (filter.required_skills) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'services',
                        'required_skills',
                        filter.required_skills,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.pricing_model) {
                where = {
                    ...where,
                pricing_model: filter.pricing_model,
            };
            }
            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.active,
            };
            }
            


      

      

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

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

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

    
};

