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

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

        const seo_entries = await db.seo_entries.create(
            {
                id: data.id || undefined,
        
        target_type: data.target_type
        ||
        null
            ,
            
        target_slug: data.target_slug
        ||
        null
            ,
            
        meta_title: data.meta_title
        ||
        null
            ,
            
        meta_description: data.meta_description
        ||
        null
            ,
            
        canonical_url: data.canonical_url
        ||
        null
            ,
            
        indexable: data.indexable
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await seo_entries.setProduct( data.product || null, {
            transaction,
        });
        
        await seo_entries.setCategory( data.category || null, {
            transaction,
        });
        
        await seo_entries.setPage( data.page || null, {
            transaction,
        });
        

        

        

        return seo_entries;
    }
    

    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_entriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                target_type: item.target_type
            ||
            null
            ,
            
                target_slug: item.target_slug
            ||
            null
            ,
            
                meta_title: item.meta_title
            ||
            null
            ,
            
                meta_description: item.meta_description
            ||
            null
            ,
            
                canonical_url: item.canonical_url
            ||
            null
            ,
            
                indexable: item.indexable
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return seo_entries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.target_type !== undefined) updatePayload.target_type = data.target_type;
        
        
        if (data.target_slug !== undefined) updatePayload.target_slug = data.target_slug;
        
        
        if (data.meta_title !== undefined) updatePayload.meta_title = data.meta_title;
        
        
        if (data.meta_description !== undefined) updatePayload.meta_description = data.meta_description;
        
        
        if (data.canonical_url !== undefined) updatePayload.canonical_url = data.canonical_url;
        
        
        if (data.indexable !== undefined) updatePayload.indexable = data.indexable;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.product !== undefined) {
            await seo_entries.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        
        if (data.category !== undefined) {
            await seo_entries.setCategory(
              
              data.category,
              
              { transaction }
            );
        }
        
        if (data.page !== undefined) {
            await seo_entries.setPage(
              
              data.page,
              
              { transaction }
            );
        }
        

        
        

        

        return seo_entries;
    }

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

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

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


        return seo_entries;
    }

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

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

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

        await seo_entries.destroy({
            transaction
        });

        return seo_entries;
    }

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

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

        if (!seo_entries) {
            return seo_entries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.product = await seo_entries.getProduct({
            transaction
        });
        
        
        output.category = await seo_entries.getCategory({
            transaction
        });
        
        
        output.page = await seo_entries.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.products,
        as: 'product',
        
        where: filter.product ? {
          [Op.or]: [
            { id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
            {
              product_name: {
                [Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.cms_pages,
        as: 'page',
        
        where: filter.page ? {
          [Op.or]: [
            { id: { [Op.in]: filter.page.split('|').map(term => Utils.uuid(term)) } },
            {
              page_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.target_slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_entries',
                        'target_slug',
                        filter.target_slug,
                    ),
                };
            }
            
            if (filter.meta_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_entries',
                        'meta_title',
                        filter.meta_title,
                    ),
                };
            }
            
            if (filter.meta_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_entries',
                        'meta_description',
                        filter.meta_description,
                    ),
                };
            }
            
            if (filter.canonical_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_entries',
                        'canonical_url',
                        filter.canonical_url,
                    ),
                };
            }
            

            
            

            

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

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


      

      

      



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

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

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

    
};

