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

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

        const pages = await db.pages.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        path: data.path
        ||
        null
            ,
            
        published: data.published
        ||
        false
        
            ,
            
        publish_start: data.publish_start
        ||
        null
            ,
            
        publish_end: data.publish_end
        ||
        null
            ,
            
        seo_description: data.seo_description
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await pages.setProject( data.project || null, {
            transaction,
        });
        
        await pages.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return 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 pagesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                path: item.path
            ||
            null
            ,
            
                published: item.published
            ||
            false
        
            ,
            
                publish_start: item.publish_start
            ||
            null
            ,
            
                publish_end: item.publish_end
            ||
            null
            ,
            
                seo_description: item.seo_description
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.path !== undefined) updatePayload.path = data.path;
        
        
        if (data.published !== undefined) updatePayload.published = data.published;
        
        
        if (data.publish_start !== undefined) updatePayload.publish_start = data.publish_start;
        
        
        if (data.publish_end !== undefined) updatePayload.publish_end = data.publish_end;
        
        
        if (data.seo_description !== undefined) updatePayload.seo_description = data.seo_description;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await pages.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await pages.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return pages;
    }

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

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

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


        return pages;
    }

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

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

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

        await pages.destroy({
            transaction
        });

        return pages;
    }

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

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

        if (!pages) {
            return pages;
        }

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

        
        
        
        
        
        
        
        
        output.layers_page = await pages.getLayers_page({
            transaction
        });
        
        
        
        output.versions_page = await pages.getVersions_page({
            transaction
        });
        
        
        output.builds_page = await pages.getBuilds_page({
            transaction
        });
        
        
        
        
        
        output.project = await pages.getProject({
            transaction
        });
        
        
        output.organizations = await 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.projects,
        as: 'project',
        
        where: filter.project ? {
          [Op.or]: [
            { id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pages',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pages',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.path) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pages',
                        'path',
                        filter.path,
                    ),
                };
            }
            
            if (filter.seo_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pages',
                        'seo_description',
                        filter.seo_description,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            publish_start: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    publish_end: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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


      

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

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

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

    
};

