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

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

        const playlists = await db.playlists.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        playlist_type: data.playlist_type
        ||
        null
            ,
            
        curator_name: data.curator_name
        ||
        null
            ,
            
        playlist_url: data.playlist_url
        ||
        null
            ,
            
        genre_focus: data.genre_focus
        ||
        null
            ,
            
        mood_tags: data.mood_tags
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await playlists.setPlatform( data.platform || null, {
            transaction,
        });
        
        await playlists.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return playlists;
    }
    

    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 playlistsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                playlist_type: item.playlist_type
            ||
            null
            ,
            
                curator_name: item.curator_name
            ||
            null
            ,
            
                playlist_url: item.playlist_url
            ||
            null
            ,
            
                genre_focus: item.genre_focus
            ||
            null
            ,
            
                mood_tags: item.mood_tags
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return playlists;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.playlist_type !== undefined) updatePayload.playlist_type = data.playlist_type;
        
        
        if (data.curator_name !== undefined) updatePayload.curator_name = data.curator_name;
        
        
        if (data.playlist_url !== undefined) updatePayload.playlist_url = data.playlist_url;
        
        
        if (data.genre_focus !== undefined) updatePayload.genre_focus = data.genre_focus;
        
        
        if (data.mood_tags !== undefined) updatePayload.mood_tags = data.mood_tags;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.platform !== undefined) {
            await playlists.setPlatform(
              
              data.platform,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await playlists.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return playlists;
    }

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

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

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


        return playlists;
    }

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

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

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

        await playlists.destroy({
            transaction
        });

        return playlists;
    }

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

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

        if (!playlists) {
            return playlists;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.playlist_placements_playlist = await playlists.getPlaylist_placements_playlist({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.platform = await playlists.getPlatform({
            transaction
        });
        
        
        output.organizations = await playlists.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.distribution_platforms,
        as: 'platform',
        
        where: filter.platform ? {
          [Op.or]: [
            { id: { [Op.in]: filter.platform.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.platform.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.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'playlists',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.curator_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'playlists',
                        'curator_name',
                        filter.curator_name,
                    ),
                };
            }
            
            if (filter.playlist_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'playlists',
                        'playlist_url',
                        filter.playlist_url,
                    ),
                };
            }
            
            if (filter.genre_focus) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'playlists',
                        'genre_focus',
                        filter.genre_focus,
                    ),
                };
            }
            
            if (filter.mood_tags) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'playlists',
                        'mood_tags',
                        filter.mood_tags,
                    ),
                };
            }
            

            
            

            

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

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


      

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

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

    
};

