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

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

        const seo_keywords = await db.seo_keywords.create(
            {
                id: data.id || undefined,
        
        keyword: data.keyword
        ||
        null
            ,
            
        intent: data.intent
        ||
        null
            ,
            
        difficulty: data.difficulty
        ||
        null
            ,
            
        search_volume: data.search_volume
        ||
        null
            ,
            
        cpc: data.cpc
        ||
        null
            ,
            
        target_url: data.target_url
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await seo_keywords.setCompany( data.company || null, {
            transaction,
        });
        
        await seo_keywords.setBusiness_unit( data.business_unit || null, {
            transaction,
        });
        

        
        await seo_keywords.setTags(data.tags || [], {
            transaction,
        });
        

        

        return seo_keywords;
    }
    

    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 seo_keywordsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                keyword: item.keyword
            ||
            null
            ,
            
                intent: item.intent
            ||
            null
            ,
            
                difficulty: item.difficulty
            ||
            null
            ,
            
                search_volume: item.search_volume
            ||
            null
            ,
            
                cpc: item.cpc
            ||
            null
            ,
            
                target_url: item.target_url
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return seo_keywords;
    }

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


        

        const updatePayload = {};
        
        if (data.keyword !== undefined) updatePayload.keyword = data.keyword;
        
        
        if (data.intent !== undefined) updatePayload.intent = data.intent;
        
        
        if (data.difficulty !== undefined) updatePayload.difficulty = data.difficulty;
        
        
        if (data.search_volume !== undefined) updatePayload.search_volume = data.search_volume;
        
        
        if (data.cpc !== undefined) updatePayload.cpc = data.cpc;
        
        
        if (data.target_url !== undefined) updatePayload.target_url = data.target_url;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await seo_keywords.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.business_unit !== undefined) {
            await seo_keywords.setBusiness_unit(
              
              data.business_unit,
              
              { transaction }
            );
        }
        

        
        
        if (data.tags !== undefined) {
            await seo_keywords.setTags(data.tags, { transaction });
        }
        

        

        return seo_keywords;
    }

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

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

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


        return seo_keywords;
    }

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

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

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

        await seo_keywords.destroy({
            transaction
        });

        return seo_keywords;
    }

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

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

        if (!seo_keywords) {
            return seo_keywords;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await seo_keywords.getCompany({
            transaction
        });
        
        
        output.business_unit = await seo_keywords.getBusiness_unit({
            transaction
        });
        
        
        output.tags = await seo_keywords.getTags({
            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 userCompanies = (user && user.companies?.id) || null;
        

        
        if (userCompanies) {
            if (options?.currentUser?.companiesId) {
                where.companiesId = options.currentUser.companiesId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.companies,
        as: 'company',
        
      },

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


      {
        model: db.tags,
        as: 'tags',
        required: false,
      },


    ];

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

            
            if (filter.keyword) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_keywords',
                        'keyword',
                        filter.keyword,
                    ),
                };
            }
            
            if (filter.target_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_keywords',
                        'target_url',
                        filter.target_url,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_keywords',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      
      if (filter.company) {
        const listItems = filter.company.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          companyId: {[Op.or]: listItems}
        };
      }
      

      


      if (filter.tags) {
        const searchTerms = filter.tags.split('|');

        include = [
          {
            model: db.tags,
            as: 'tags_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


            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.companiesId;
        }
        

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

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

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

    
};

