
const db = require('../models');
const Utils = require('../utils');
const {
  applyRuntimeEnvironment,
  applyRuntimeProjectFilter,
} = require('./runtime-context');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Tour_pagesDBApi {
    

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

        const tour_pages = await db.tour_pages.create(
            {
                id: data.id || undefined,
        
        environment: data.environment
        ||
        null
            ,
            
        source_key: data.source_key
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        sort_order: data.sort_order
        ||
        null
            ,
            
        background_image_url: data.background_image_url
        ||
        null
            ,
            
        background_video_url: data.background_video_url
        ||
        null
            ,
            
        background_audio_url: data.background_audio_url
        ||
        null
            ,
            
        background_loop: data.background_loop
        ||
        false
        
            ,
            
        requires_auth: data.requires_auth
        ||
        false
        
            ,
            
        ui_schema_json: data.ui_schema_json
        ||
        null
            ,
            projectId,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await tour_pages.setProject(projectId, {
            transaction,
        });
        

        

        

        return tour_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 tour_pagesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                environment: item.environment
            ||
            null
            ,
            
                source_key: item.source_key
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                sort_order: item.sort_order
            ||
            null
            ,
            
                background_image_url: item.background_image_url
            ||
            null
            ,
            
                background_video_url: item.background_video_url
            ||
            null
            ,
            
                background_audio_url: item.background_audio_url
            ||
            null
            ,
            
                background_loop: item.background_loop
            ||
            false
        
            ,
            
                requires_auth: item.requires_auth
            ||
            false
        
            ,
            
                ui_schema_json: item.ui_schema_json
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return tour_pages;
    }

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

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


        

        const updatePayload = {};
        
        if (data.environment !== undefined) updatePayload.environment = data.environment;
        
        
        if (data.source_key !== undefined) updatePayload.source_key = data.source_key;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        if (data.background_image_url !== undefined) updatePayload.background_image_url = data.background_image_url;
        
        
        if (data.background_video_url !== undefined) updatePayload.background_video_url = data.background_video_url;
        
        
        if (data.background_audio_url !== undefined) updatePayload.background_audio_url = data.background_audio_url;
        
        
        if (data.background_loop !== undefined) updatePayload.background_loop = data.background_loop;
        
        
        if (data.requires_auth !== undefined) updatePayload.requires_auth = data.requires_auth;
        
        
        if (data.ui_schema_json !== undefined) updatePayload.ui_schema_json = data.ui_schema_json;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return tour_pages;
    }

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

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

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


        return tour_pages;
    }

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

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

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

        await tour_pages.destroy({
            transaction
        });

        return tour_pages;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;
        const queryWhere = applyRuntimeEnvironment({ ...where }, options);
        const projectInclude = applyRuntimeProjectFilter(
            {
                model: db.projects,
                as: 'project',
            },
            options,
        );

        const tour_pages = await db.tour_pages.findOne(
            { where: queryWhere, include: [projectInclude], transaction },
        );

        if (!tour_pages) {
            return tour_pages;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.page_elements_page = await tour_pages.getPage_elements_page({
            transaction
        });
        
        
        output.page_links_from_page = await tour_pages.getPage_links_from_page({
            transaction
        });
        
        output.page_links_to_page = await tour_pages.getPage_links_to_page({
            transaction
        });
        
        
        
        
        
        
        
        
        output.project = await tour_pages.getProject({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        filter = filter || {};
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

    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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];
        include[0] = applyRuntimeProjectFilter(include[0], options);

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

            
            if (filter.source_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tour_pages',
                        'source_key',
                        filter.source_key,
                    ),
                };
            }
            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tour_pages',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tour_pages',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.background_image_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tour_pages',
                        'background_image_url',
                        filter.background_image_url,
                    ),
                };
            }
            
            if (filter.background_video_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tour_pages',
                        'background_video_url',
                        filter.background_video_url,
                    ),
                };
            }
            
            if (filter.background_audio_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tour_pages',
                        'background_audio_url',
                        filter.background_audio_url,
                    ),
                };
            }
            
            if (filter.ui_schema_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tour_pages',
                        'ui_schema_json',
                        filter.ui_schema_json,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.environment) {
                where = {
                    ...where,
                environment: filter.environment,
            };
            }
            
            if (filter.background_loop) {
                where = {
                    ...where,
                background_loop: filter.background_loop,
            };
            }
            
            if (filter.requires_auth) {
                where = {
                    ...where,
                requires_auth: filter.requires_auth,
            };
            }
            


      



            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,
                        },
                    };
                }
            }
        }
        
        where = applyRuntimeEnvironment(where, options);

        

        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.tour_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(
                        'tour_pages',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};
