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

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

        const tip_pages = await db.tip_pages.create(
            {
                id: data.id || undefined,
        
        slug: data.slug
        ||
        null
            ,
            
        headline: data.headline
        ||
        null
            ,
            
        thank_you_message: data.thank_you_message
        ||
        null
            ,
            
        background_type: data.background_type
        ||
        null
            ,
            
        background_value: data.background_value
        ||
        null
            ,
            
        accent_color_hex: data.accent_color_hex
        ||
        null
            ,
            
        preset_amount_1: data.preset_amount_1
        ||
        null
            ,
            
        preset_amount_2: data.preset_amount_2
        ||
        null
            ,
            
        preset_amount_3: data.preset_amount_3
        ||
        null
            ,
            
        allow_custom_amount: data.allow_custom_amount
        ||
        false
        
            ,
            
        minimum_amount: data.minimum_amount
        ||
        null
            ,
            
        tts_enabled: data.tts_enabled
        ||
        false
        
            ,
            
        tts_voice: data.tts_voice
        ||
        null
            ,
            
        show_supporter_feed: data.show_supporter_feed
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await tip_pages.setCreator( data.creator || null, {
            transaction,
        });
        
        await tip_pages.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return tip_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 tip_pagesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                slug: item.slug
            ||
            null
            ,
            
                headline: item.headline
            ||
            null
            ,
            
                thank_you_message: item.thank_you_message
            ||
            null
            ,
            
                background_type: item.background_type
            ||
            null
            ,
            
                background_value: item.background_value
            ||
            null
            ,
            
                accent_color_hex: item.accent_color_hex
            ||
            null
            ,
            
                preset_amount_1: item.preset_amount_1
            ||
            null
            ,
            
                preset_amount_2: item.preset_amount_2
            ||
            null
            ,
            
                preset_amount_3: item.preset_amount_3
            ||
            null
            ,
            
                allow_custom_amount: item.allow_custom_amount
            ||
            false
        
            ,
            
                minimum_amount: item.minimum_amount
            ||
            null
            ,
            
                tts_enabled: item.tts_enabled
            ||
            false
        
            ,
            
                tts_voice: item.tts_voice
            ||
            null
            ,
            
                show_supporter_feed: item.show_supporter_feed
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.headline !== undefined) updatePayload.headline = data.headline;
        
        
        if (data.thank_you_message !== undefined) updatePayload.thank_you_message = data.thank_you_message;
        
        
        if (data.background_type !== undefined) updatePayload.background_type = data.background_type;
        
        
        if (data.background_value !== undefined) updatePayload.background_value = data.background_value;
        
        
        if (data.accent_color_hex !== undefined) updatePayload.accent_color_hex = data.accent_color_hex;
        
        
        if (data.preset_amount_1 !== undefined) updatePayload.preset_amount_1 = data.preset_amount_1;
        
        
        if (data.preset_amount_2 !== undefined) updatePayload.preset_amount_2 = data.preset_amount_2;
        
        
        if (data.preset_amount_3 !== undefined) updatePayload.preset_amount_3 = data.preset_amount_3;
        
        
        if (data.allow_custom_amount !== undefined) updatePayload.allow_custom_amount = data.allow_custom_amount;
        
        
        if (data.minimum_amount !== undefined) updatePayload.minimum_amount = data.minimum_amount;
        
        
        if (data.tts_enabled !== undefined) updatePayload.tts_enabled = data.tts_enabled;
        
        
        if (data.tts_voice !== undefined) updatePayload.tts_voice = data.tts_voice;
        
        
        if (data.show_supporter_feed !== undefined) updatePayload.show_supporter_feed = data.show_supporter_feed;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.creator !== undefined) {
            await tip_pages.setCreator(
              
              data.creator,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await tip_pages.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return tip_pages;
    }

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

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

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


        return tip_pages;
    }

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

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

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

        await tip_pages.destroy({
            transaction
        });

        return tip_pages;
    }

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

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

        if (!tip_pages) {
            return tip_pages;
        }

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

        
        
        
        
        
        output.creator_profiles_tip_page = await tip_pages.getCreator_profiles_tip_page({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tips_tip_page = await tip_pages.getTips_tip_page({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.creator = await tip_pages.getCreator({
            transaction
        });
        
        
        output.organizations = await tip_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.creator_profiles,
        as: 'creator',
        
        where: filter.creator ? {
          [Op.or]: [
            { id: { [Op.in]: filter.creator.split('|').map(term => Utils.uuid(term)) } },
            {
              handle: {
                [Op.or]: filter.creator.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.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tip_pages',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.headline) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tip_pages',
                        'headline',
                        filter.headline,
                    ),
                };
            }
            
            if (filter.thank_you_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tip_pages',
                        'thank_you_message',
                        filter.thank_you_message,
                    ),
                };
            }
            
            if (filter.background_value) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tip_pages',
                        'background_value',
                        filter.background_value,
                    ),
                };
            }
            
            if (filter.accent_color_hex) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tip_pages',
                        'accent_color_hex',
                        filter.accent_color_hex,
                    ),
                };
            }
            
            if (filter.tts_voice) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tip_pages',
                        'tts_voice',
                        filter.tts_voice,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.background_type) {
                where = {
                    ...where,
                background_type: filter.background_type,
            };
            }
            
            if (filter.allow_custom_amount) {
                where = {
                    ...where,
                allow_custom_amount: filter.allow_custom_amount,
            };
            }
            
            if (filter.tts_enabled) {
                where = {
                    ...where,
                tts_enabled: filter.tts_enabled,
            };
            }
            
            if (filter.show_supporter_feed) {
                where = {
                    ...where,
                show_supporter_feed: filter.show_supporter_feed,
            };
            }
            


      

      
      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.tip_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(
                        'tip_pages',
                        'slug',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

