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

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

        const testimonials = await db.testimonials.create(
            {
                id: data.id || undefined,
        
        customer_name: data.customer_name
        ||
        null
            ,
            
        customer_title: data.customer_title
        ||
        null
            ,
            
        company_name: data.company_name
        ||
        null
            ,
            
        testimonial_text: data.testimonial_text
        ||
        null
            ,
            
        rating: data.rating
        ||
        null
            ,
            
        is_published: data.is_published
        ||
        false
        
            ,
            
        sort_order: data.sort_order
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await testimonials.setProject( data.project || null, {
            transaction,
        });
        

        

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

        return testimonials;
    }
    

    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 testimonialsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                customer_name: item.customer_name
            ||
            null
            ,
            
                customer_title: item.customer_title
            ||
            null
            ,
            
                company_name: item.company_name
            ||
            null
            ,
            
                testimonial_text: item.testimonial_text
            ||
            null
            ,
            
                rating: item.rating
            ||
            null
            ,
            
                is_published: item.is_published
            ||
            false
        
            ,
            
                sort_order: item.sort_order
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return testimonials;
    }

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

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


        

        const updatePayload = {};
        
        if (data.customer_name !== undefined) updatePayload.customer_name = data.customer_name;
        
        
        if (data.customer_title !== undefined) updatePayload.customer_title = data.customer_title;
        
        
        if (data.company_name !== undefined) updatePayload.company_name = data.company_name;
        
        
        if (data.testimonial_text !== undefined) updatePayload.testimonial_text = data.testimonial_text;
        
        
        if (data.rating !== undefined) updatePayload.rating = data.rating;
        
        
        if (data.is_published !== undefined) updatePayload.is_published = data.is_published;
        
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await testimonials.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        

        
        

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

        return testimonials;
    }

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

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

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


        return testimonials;
    }

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

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

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

        await testimonials.destroy({
            transaction
        });

        return testimonials;
    }

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

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

        if (!testimonials) {
            return testimonials;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.customer_images = await testimonials.getCustomer_images({
            transaction
        });
        
        
        output.project = await testimonials.getProject({
            transaction
        });
        
        

        return output;
    }

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

        

        

        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)) } },
            {
              title: {
                [Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.customer_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'testimonials',
                        'customer_name',
                        filter.customer_name,
                    ),
                };
            }
            
            if (filter.customer_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'testimonials',
                        'customer_title',
                        filter.customer_title,
                    ),
                };
            }
            
            if (filter.company_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'testimonials',
                        'company_name',
                        filter.company_name,
                    ),
                };
            }
            
            if (filter.testimonial_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'testimonials',
                        'testimonial_text',
                        filter.testimonial_text,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      



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

        

        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.testimonials.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, ) {
        let where = {};
        
        

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

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

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

    
};

