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

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

        const seo_pages = await db.seo_pages.create(
            {
                id: data.id || undefined,
        
        page_key: data.page_key
        ||
        null
            ,
            
        title_ar: data.title_ar
        ||
        null
            ,
            
        description_ar: data.description_ar
        ||
        null
            ,
            
        canonical_url: data.canonical_url
        ||
        null
            ,
            
        indexable: data.indexable
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return seo_pages;
    }
    

    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_pagesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                page_key: item.page_key
            ||
            null
            ,
            
                title_ar: item.title_ar
            ||
            null
            ,
            
                description_ar: item.description_ar
            ||
            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_pages = await db.seo_pages.bulkCreate(seo_pagesData, { transaction });

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

        return seo_pages;
    }

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

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


        

        const updatePayload = {};
        
        if (data.page_key !== undefined) updatePayload.page_key = data.page_key;
        
        
        if (data.title_ar !== undefined) updatePayload.title_ar = data.title_ar;
        
        
        if (data.description_ar !== undefined) updatePayload.description_ar = data.description_ar;
        
        
        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_pages.update(updatePayload, {transaction});

        
        

        
        

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

        return seo_pages;
    }

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

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

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


        return seo_pages;
    }

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

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

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

        await seo_pages.destroy({
            transaction
        });

        return seo_pages;
    }

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

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

        if (!seo_pages) {
            return seo_pages;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.structured_data_jsonld = await seo_pages.getStructured_data_jsonld({
            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.file,
        as: 'structured_data_jsonld',
      },

    ];

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

            
            if (filter.title_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_pages',
                        'title_ar',
                        filter.title_ar,
                    ),
                };
            }
            
            if (filter.description_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_pages',
                        'description_ar',
                        filter.description_ar,
                    ),
                };
            }
            
            if (filter.canonical_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'seo_pages',
                        'canonical_url',
                        filter.canonical_url,
                    ),
                };
            }
            

            
            

            

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

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

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

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

    
};

