
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,
        
        client_name: data.client_name
        ||
        null
            ,
            
        company_name: data.company_name
        ||
        null
            ,
            
        country: data.country
        ||
        null
            ,
            
        quote: data.quote
        ||
        null
            ,
            
        rating: data.rating
        ||
        null
            ,
            
        is_featured: data.is_featured
        ||
        false
        
            ,
            
        is_published: data.is_published
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await testimonials.setPage( data.page || null, {
            transaction,
        });
        

        

        

        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,
                
                client_name: item.client_name
            ||
            null
            ,
            
                company_name: item.company_name
            ||
            null
            ,
            
                country: item.country
            ||
            null
            ,
            
                quote: item.quote
            ||
            null
            ,
            
                rating: item.rating
            ||
            null
            ,
            
                is_featured: item.is_featured
            ||
            false
        
            ,
            
                is_published: item.is_published
            ||
            false
        
            ,
            
            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
        

        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.client_name !== undefined) updatePayload.client_name = data.client_name;
        
        
        if (data.company_name !== undefined) updatePayload.company_name = data.company_name;
        
        
        if (data.country !== undefined) updatePayload.country = data.country;
        
        
        if (data.quote !== undefined) updatePayload.quote = data.quote;
        
        
        if (data.rating !== undefined) updatePayload.rating = data.rating;
        
        
        if (data.is_featured !== undefined) updatePayload.is_featured = data.is_featured;
        
        
        if (data.is_published !== undefined) updatePayload.is_published = data.is_published;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.page !== undefined) {
            await testimonials.setPage(
              
              data.page,
              
              { transaction }
            );
        }
        

        
        

        

        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.page = await testimonials.getPage({
            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.pages,
        as: 'page',
        
        where: filter.page ? {
          [Op.or]: [
            { id: { [Op.in]: filter.page.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.page.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.client_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'testimonials',
                        'client_name',
                        filter.client_name,
                    ),
                };
            }
            
            if (filter.company_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'testimonials',
                        'company_name',
                        filter.company_name,
                    ),
                };
            }
            
            if (filter.country) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'testimonials',
                        'country',
                        filter.country,
                    ),
                };
            }
            
            if (filter.quote) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'testimonials',
                        'quote',
                        filter.quote,
                    ),
                };
            }
            

            
            

            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.is_featured) {
                where = {
                    ...where,
                is_featured: filter.is_featured,
            };
            }
            
            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',
                        'client_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

