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

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

        const smart_links = await db.smart_links.create(
            {
                id: data.id || undefined,
        
        slug: data.slug
        ||
        null
            ,
            
        page_title: data.page_title
        ||
        null
            ,
            
        custom_text: data.custom_text
        ||
        null
            ,
            
        theme_color: data.theme_color
        ||
        null
            ,
            
        is_public: data.is_public
        ||
        false
        
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await smart_links.setRelease( data.release || null, {
            transaction,
        });
        
        await smart_links.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return smart_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 smart_linksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                slug: item.slug
            ||
            null
            ,
            
                page_title: item.page_title
            ||
            null
            ,
            
                custom_text: item.custom_text
            ||
            null
            ,
            
                theme_color: item.theme_color
            ||
            null
            ,
            
                is_public: item.is_public
            ||
            false
        
            ,
            
                published_at: item.published_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return smart_links;
    }

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


        

        const updatePayload = {};
        
        if (data.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.page_title !== undefined) updatePayload.page_title = data.page_title;
        
        
        if (data.custom_text !== undefined) updatePayload.custom_text = data.custom_text;
        
        
        if (data.theme_color !== undefined) updatePayload.theme_color = data.theme_color;
        
        
        if (data.is_public !== undefined) updatePayload.is_public = data.is_public;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.release !== undefined) {
            await smart_links.setRelease(
              
              data.release,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await smart_links.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return smart_links;
    }

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

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

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


        return smart_links;
    }

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

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

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

        await smart_links.destroy({
            transaction
        });

        return smart_links;
    }

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

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

        if (!smart_links) {
            return smart_links;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.smart_link_destinations_smart_link = await smart_links.getSmart_link_destinations_smart_link({
            transaction
        });
        
        
        output.smart_link_clicks_smart_link = await smart_links.getSmart_link_clicks_smart_link({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.release = await smart_links.getRelease({
            transaction
        });
        
        
        output.background_image = await smart_links.getBackground_image({
            transaction
        });
        
        
        output.artist_photo = await smart_links.getArtist_photo({
            transaction
        });
        
        
        output.organizations = await smart_links.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.releases,
        as: 'release',
        
        where: filter.release ? {
          [Op.or]: [
            { id: { [Op.in]: filter.release.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.release.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

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

    ];

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

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

            
            

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

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

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

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

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


      

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

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

        const records = await db.smart_links.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,
        }));
    }

    
};

