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

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

        const store_pages = await db.store_pages.create(
            {
                id: data.id || undefined,
        
        page_title: data.page_title
        ||
        null
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        page_type: data.page_type
        ||
        null
            ,
            
        page_status: data.page_status
        ||
        null
            ,
            
        content: data.content
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await store_pages.setReseller_store( data.reseller_store || null, {
            transaction,
        });
        
        await store_pages.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return store_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 store_pagesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                page_title: item.page_title
            ||
            null
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                page_type: item.page_type
            ||
            null
            ,
            
                page_status: item.page_status
            ||
            null
            ,
            
                content: item.content
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return store_pages;
    }

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


        

        const updatePayload = {};
        
        if (data.page_title !== undefined) updatePayload.page_title = data.page_title;
        
        
        if (data.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.page_type !== undefined) updatePayload.page_type = data.page_type;
        
        
        if (data.page_status !== undefined) updatePayload.page_status = data.page_status;
        
        
        if (data.content !== undefined) updatePayload.content = data.content;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.reseller_store !== undefined) {
            await store_pages.setReseller_store(
              
              data.reseller_store,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await store_pages.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return store_pages;
    }

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

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

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


        return store_pages;
    }

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

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

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

        await store_pages.destroy({
            transaction
        });

        return store_pages;
    }

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

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

        if (!store_pages) {
            return store_pages;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.reseller_store = await store_pages.getReseller_store({
            transaction
        });
        
        
        output.page_images = await store_pages.getPage_images({
            transaction
        });
        
        
        output.organizations = await store_pages.getOrganizations({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



      {
        model: db.file,
        as: 'page_images',
      },

    ];

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

            
            if (filter.page_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'store_pages',
                        'page_title',
                        filter.page_title,
                    ),
                };
            }
            
            if (filter.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'store_pages',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.content) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'store_pages',
                        'content',
                        filter.content,
                    ),
                };
            }
            

            
            

            

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

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


      

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

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



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

        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.store_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'store_pages',
                        'page_title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

