
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,
        
        entity_type: data.entity_type
        ||
        null
            ,
            
        entity_key: data.entity_key
        ||
        null
            ,
            
        meta_title_ar: data.meta_title_ar
        ||
        null
            ,
            
        meta_title_en: data.meta_title_en
        ||
        null
            ,
            
        meta_description_ar: data.meta_description_ar
        ||
        null
            ,
            
        meta_description_en: data.meta_description_en
        ||
        null
            ,
            
        canonical_url: data.canonical_url
        ||
        null
            ,
            
        open_graph_image_url: data.open_graph_image_url
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { 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,
                
                entity_type: item.entity_type
            ||
            null
            ,
            
                entity_key: item.entity_key
            ||
            null
            ,
            
                meta_title_ar: item.meta_title_ar
            ||
            null
            ,
            
                meta_title_en: item.meta_title_en
            ||
            null
            ,
            
                meta_description_ar: item.meta_description_ar
            ||
            null
            ,
            
                meta_description_en: item.meta_description_en
            ||
            null
            ,
            
                canonical_url: item.canonical_url
            ||
            null
            ,
            
                open_graph_image_url: item.open_graph_image_url
            ||
            null
            ,
            
            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.entity_type !== undefined) updatePayload.entity_type = data.entity_type;
        
        
        if (data.entity_key !== undefined) updatePayload.entity_key = data.entity_key;
        
        
        if (data.meta_title_ar !== undefined) updatePayload.meta_title_ar = data.meta_title_ar;
        
        
        if (data.meta_title_en !== undefined) updatePayload.meta_title_en = data.meta_title_en;
        
        
        if (data.meta_description_ar !== undefined) updatePayload.meta_description_ar = data.meta_description_ar;
        
        
        if (data.meta_description_en !== undefined) updatePayload.meta_description_en = data.meta_description_en;
        
        
        if (data.canonical_url !== undefined) updatePayload.canonical_url = data.canonical_url;
        
        
        if (data.open_graph_image_url !== undefined) updatePayload.open_graph_image_url = data.open_graph_image_url;
        
        
        updatePayload.updatedById = currentUser.id;

        await seo_entries.update(updatePayload, {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});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        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 = [



    ];

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

            
            if (filter.entity_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_entries',
                        'entity_key',
                        filter.entity_key,
                    ),
                };
            }
            
            if (filter.meta_title_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_entries',
                        'meta_title_ar',
                        filter.meta_title_ar,
                    ),
                };
            }
            
            if (filter.meta_title_en) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_entries',
                        'meta_title_en',
                        filter.meta_title_en,
                    ),
                };
            }
            
            if (filter.meta_description_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_entries',
                        'meta_description_ar',
                        filter.meta_description_ar,
                    ),
                };
            }
            
            if (filter.meta_description_en) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_entries',
                        'meta_description_en',
                        filter.meta_description_en,
                    ),
                };
            }
            
            if (filter.canonical_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_entries',
                        'canonical_url',
                        filter.canonical_url,
                    ),
                };
            }
            
            if (filter.open_graph_image_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_entries',
                        'open_graph_image_url',
                        filter.open_graph_image_url,
                    ),
                };
            }
            

            
            

            

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

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




            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',
                        'entity_key',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

