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

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

        const royalty_lines = await db.royalty_lines.create(
            {
                id: data.id || undefined,
        
        territory: data.territory
        ||
        null
            ,
            
        store_name: data.store_name
        ||
        null
            ,
            
        quantity: data.quantity
        ||
        null
            ,
            
        unit_rate: data.unit_rate
        ||
        null
            ,
            
        gross_amount: data.gross_amount
        ||
        null
            ,
            
        net_amount: data.net_amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        event_at: data.event_at
        ||
        null
            ,
            
        usage_type: data.usage_type
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await royalty_lines.setRoyalty_report( data.royalty_report || null, {
            transaction,
        });
        
        await royalty_lines.setRelease( data.release || null, {
            transaction,
        });
        
        await royalty_lines.setTrack( data.track || null, {
            transaction,
        });
        
        await royalty_lines.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return royalty_lines;
    }
    

    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 royalty_linesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                territory: item.territory
            ||
            null
            ,
            
                store_name: item.store_name
            ||
            null
            ,
            
                quantity: item.quantity
            ||
            null
            ,
            
                unit_rate: item.unit_rate
            ||
            null
            ,
            
                gross_amount: item.gross_amount
            ||
            null
            ,
            
                net_amount: item.net_amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                event_at: item.event_at
            ||
            null
            ,
            
                usage_type: item.usage_type
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return royalty_lines;
    }

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


        

        const updatePayload = {};
        
        if (data.territory !== undefined) updatePayload.territory = data.territory;
        
        
        if (data.store_name !== undefined) updatePayload.store_name = data.store_name;
        
        
        if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
        
        
        if (data.unit_rate !== undefined) updatePayload.unit_rate = data.unit_rate;
        
        
        if (data.gross_amount !== undefined) updatePayload.gross_amount = data.gross_amount;
        
        
        if (data.net_amount !== undefined) updatePayload.net_amount = data.net_amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.event_at !== undefined) updatePayload.event_at = data.event_at;
        
        
        if (data.usage_type !== undefined) updatePayload.usage_type = data.usage_type;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.royalty_report !== undefined) {
            await royalty_lines.setRoyalty_report(
              
              data.royalty_report,
              
              { transaction }
            );
        }
        
        if (data.release !== undefined) {
            await royalty_lines.setRelease(
              
              data.release,
              
              { transaction }
            );
        }
        
        if (data.track !== undefined) {
            await royalty_lines.setTrack(
              
              data.track,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await royalty_lines.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return royalty_lines;
    }

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

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

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


        return royalty_lines;
    }

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

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

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

        await royalty_lines.destroy({
            transaction
        });

        return royalty_lines;
    }

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

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

        if (!royalty_lines) {
            return royalty_lines;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.royalty_report = await royalty_lines.getRoyalty_report({
            transaction
        });
        
        
        output.release = await royalty_lines.getRelease({
            transaction
        });
        
        
        output.track = await royalty_lines.getTrack({
            transaction
        });
        
        
        output.organizations = await royalty_lines.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.royalty_reports,
        as: 'royalty_report',
        
        where: filter.royalty_report ? {
          [Op.or]: [
            { id: { [Op.in]: filter.royalty_report.split('|').map(term => Utils.uuid(term)) } },
            {
              source_reference: {
                [Op.or]: filter.royalty_report.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.territory) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'royalty_lines',
                        'territory',
                        filter.territory,
                    ),
                };
            }
            
            if (filter.store_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'royalty_lines',
                        'store_name',
                        filter.store_name,
                    ),
                };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'royalty_lines',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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


      

      

      

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

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

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

    
};

