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



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

module.exports = class Page_linksDBApi {
    

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

        const page_links = await db.page_links.create(
            {
                id: data.id || undefined,
        
        direction: data.direction
        ||
        null
            ,
            
        external_url: data.external_url
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        trigger_selector: data.trigger_selector
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await page_links.setFrom_page( data.from_page || null, {
            transaction,
        });
        
        await page_links.setTo_page( data.to_page || null, {
            transaction,
        });
        
        await page_links.setTransition( data.transition || null, {
            transaction,
        });
        

        

        

        return page_links;
    }
    

    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 page_linksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                direction: item.direction
            ||
            null
            ,
            
                external_url: item.external_url
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                trigger_selector: item.trigger_selector
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return page_links;
    }

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

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


        

        const updatePayload = {};
        
        if (data.direction !== undefined) updatePayload.direction = data.direction;
        
        
        if (data.external_url !== undefined) updatePayload.external_url = data.external_url;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.trigger_selector !== undefined) updatePayload.trigger_selector = data.trigger_selector;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.from_page !== undefined) {
            await page_links.setFrom_page(
              
              data.from_page,
              
              { transaction }
            );
        }
        
        if (data.to_page !== undefined) {
            await page_links.setTo_page(
              
              data.to_page,
              
              { transaction }
            );
        }
        
        if (data.transition !== undefined) {
            await page_links.setTransition(
              
              data.transition,
              
              { transaction }
            );
        }
        

        
        

        

        return page_links;
    }

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

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

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


        return page_links;
    }

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

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

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

        await page_links.destroy({
            transaction
        });

        return page_links;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;
        const runtimeEnvironment = getRuntimeEnvironment(options);
        const runtimeProjectSlug = getRuntimeProjectSlug(options);
        const buildProjectInclude = () => (
            runtimeProjectSlug
                ? [{
                    model: db.projects,
                    as: 'project',
                    required: true,
                    where: { slug: runtimeProjectSlug },
                }]
                : []
        );

        const page_links = await db.page_links.findOne(
            {
                where,
                include: [
                    {
                        model: db.tour_pages,
                        as: 'from_page',
                        required: Boolean(runtimeEnvironment || runtimeProjectSlug),
                        where: runtimeEnvironment ? { environment: runtimeEnvironment } : {},
                        include: buildProjectInclude(),
                    },
                    {
                        model: db.transitions,
                        as: 'transition',
                        required: false,
                        where: runtimeEnvironment ? { environment: runtimeEnvironment } : {},
                        include: buildProjectInclude(),
                    },
                ],
                transaction,
            },
        );

        if (!page_links) {
            return page_links;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.from_page = await page_links.getFrom_page({
            transaction
        });
        
        
        output.to_page = await page_links.getTo_page({
            transaction
        });
        
        
        output.transition = await page_links.getTransition({
            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.tour_pages,
        as: 'from_page',
        
        where: filter.from_page ? {
          [Op.or]: [
            { id: { [Op.in]: filter.from_page.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.from_page.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];
        const runtimeEnvironment = getRuntimeEnvironment(options);
        const runtimeProjectSlug = getRuntimeProjectSlug(options);

        if (runtimeEnvironment) {
            include[0].where = {
                ...(include[0].where || {}),
                environment: runtimeEnvironment,
            };
            include[0].required = true;
            include[1].where = {
                ...(include[1].where || {}),
                environment: runtimeEnvironment,
            };
            include[2].where = {
                ...(include[2].where || {}),
                environment: runtimeEnvironment,
            };
            include[2].required = false;
        }

        if (runtimeProjectSlug) {
            include[0].include = [{
                model: db.projects,
                as: 'project',
                required: true,
                where: { slug: runtimeProjectSlug },
            }];
            include[0].required = true;
            include[1].include = [{
                model: db.projects,
                as: 'project',
                required: true,
                where: { slug: runtimeProjectSlug },
            }];
            include[2].include = [{
                model: db.projects,
                as: 'project',
                required: true,
                where: { slug: runtimeProjectSlug },
            }];
            include[2].required = false;
        }

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

            
            if (filter.external_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'page_links',
                        'external_url',
                        filter.external_url,
                    ),
                };
            }
            
            if (filter.trigger_selector) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'page_links',
                        'trigger_selector',
                        filter.trigger_selector,
                    ),
                };
            }
            

            
            

            

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

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


      

      

      



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

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

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

    
};
