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

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

        const pitch_requests = await db.pitch_requests.create(
            {
                id: data.id || undefined,
        
        pitch_title: data.pitch_title
        ||
        null
            ,
            
        pitch_text: data.pitch_text
        ||
        null
            ,
            
        mood: data.mood
        ||
        null
            ,
            
        similar_artists: data.similar_artists
        ||
        null
            ,
            
        achievements: data.achievements
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        decided_at: data.decided_at
        ||
        null
            ,
            
        decision_notes: data.decision_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await pitch_requests.setTrack( data.track || null, {
            transaction,
        });
        
        await pitch_requests.setArtist_profile( data.artist_profile || null, {
            transaction,
        });
        
        await pitch_requests.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await pitch_requests.setTarget_playlists(data.target_playlists || [], {
            transaction,
        });
        

        

        return pitch_requests;
    }
    

    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 pitch_requestsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                pitch_title: item.pitch_title
            ||
            null
            ,
            
                pitch_text: item.pitch_text
            ||
            null
            ,
            
                mood: item.mood
            ||
            null
            ,
            
                similar_artists: item.similar_artists
            ||
            null
            ,
            
                achievements: item.achievements
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                decided_at: item.decided_at
            ||
            null
            ,
            
                decision_notes: item.decision_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return pitch_requests;
    }

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


        

        const updatePayload = {};
        
        if (data.pitch_title !== undefined) updatePayload.pitch_title = data.pitch_title;
        
        
        if (data.pitch_text !== undefined) updatePayload.pitch_text = data.pitch_text;
        
        
        if (data.mood !== undefined) updatePayload.mood = data.mood;
        
        
        if (data.similar_artists !== undefined) updatePayload.similar_artists = data.similar_artists;
        
        
        if (data.achievements !== undefined) updatePayload.achievements = data.achievements;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.decided_at !== undefined) updatePayload.decided_at = data.decided_at;
        
        
        if (data.decision_notes !== undefined) updatePayload.decision_notes = data.decision_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.track !== undefined) {
            await pitch_requests.setTrack(
              
              data.track,
              
              { transaction }
            );
        }
        
        if (data.artist_profile !== undefined) {
            await pitch_requests.setArtist_profile(
              
              data.artist_profile,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await pitch_requests.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.target_playlists !== undefined) {
            await pitch_requests.setTarget_playlists(data.target_playlists, { transaction });
        }
        

        

        return pitch_requests;
    }

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

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

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


        return pitch_requests;
    }

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

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

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

        await pitch_requests.destroy({
            transaction
        });

        return pitch_requests;
    }

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

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

        if (!pitch_requests) {
            return pitch_requests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.track = await pitch_requests.getTrack({
            transaction
        });
        
        
        output.artist_profile = await pitch_requests.getArtist_profile({
            transaction
        });
        
        
        output.target_playlists = await pitch_requests.getTarget_playlists({
            transaction
        });
        
        
        output.organizations = await pitch_requests.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.tracks,
        as: 'track',
        
        where: filter.track ? {
          [Op.or]: [
            { id: { [Op.in]: filter.track.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.track.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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


      {
        model: db.playlists,
        as: 'target_playlists',
        required: false,
      },


    ];

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

            
            if (filter.pitch_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pitch_requests',
                        'pitch_title',
                        filter.pitch_title,
                    ),
                };
            }
            
            if (filter.pitch_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pitch_requests',
                        'pitch_text',
                        filter.pitch_text,
                    ),
                };
            }
            
            if (filter.mood) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pitch_requests',
                        'mood',
                        filter.mood,
                    ),
                };
            }
            
            if (filter.similar_artists) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pitch_requests',
                        'similar_artists',
                        filter.similar_artists,
                    ),
                };
            }
            
            if (filter.achievements) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pitch_requests',
                        'achievements',
                        filter.achievements,
                    ),
                };
            }
            
            if (filter.decision_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pitch_requests',
                        'decision_notes',
                        filter.decision_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      


      if (filter.target_playlists) {
        const searchTerms = filter.target_playlists.split('|');

        include = [
          {
            model: db.playlists,
            as: 'target_playlists_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

