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

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

        const royalty_reports = await db.royalty_reports.create(
            {
                id: data.id || undefined,
        
        period_start_at: data.period_start_at
        ||
        null
            ,
            
        period_end_at: data.period_end_at
        ||
        null
            ,
            
        source_type: data.source_type
        ||
        null
            ,
            
        source_reference: data.source_reference
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        error_details: data.error_details
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

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

        return royalty_reports;
    }
    

    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_reportsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                period_start_at: item.period_start_at
            ||
            null
            ,
            
                period_end_at: item.period_end_at
            ||
            null
            ,
            
                source_type: item.source_type
            ||
            null
            ,
            
                source_reference: item.source_reference
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                error_details: item.error_details
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return royalty_reports;
    }

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


        

        const updatePayload = {};
        
        if (data.period_start_at !== undefined) updatePayload.period_start_at = data.period_start_at;
        
        
        if (data.period_end_at !== undefined) updatePayload.period_end_at = data.period_end_at;
        
        
        if (data.source_type !== undefined) updatePayload.source_type = data.source_type;
        
        
        if (data.source_reference !== undefined) updatePayload.source_reference = data.source_reference;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.error_details !== undefined) updatePayload.error_details = data.error_details;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return royalty_reports;
    }

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

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

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


        return royalty_reports;
    }

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

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

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

        await royalty_reports.destroy({
            transaction
        });

        return royalty_reports;
    }

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

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

        if (!royalty_reports) {
            return royalty_reports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.royalty_lines_royalty_report = await royalty_reports.getRoyalty_lines_royalty_report({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.artist_profile = await royalty_reports.getArtist_profile({
            transaction
        });
        
        
        output.platform = await royalty_reports.getPlatform({
            transaction
        });
        
        
        output.source_file = await royalty_reports.getSource_file({
            transaction
        });
        
        
        output.organizations = await royalty_reports.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.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.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',
        
      },



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

    ];

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

            
            if (filter.source_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'royalty_reports',
                        'source_reference',
                        filter.source_reference,
                    ),
                };
            }
            
            if (filter.error_details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'royalty_reports',
                        'error_details',
                        filter.error_details,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            period_start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    period_end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

            
            if (filter.source_type) {
                where = {
                    ...where,
                source_type: filter.source_type,
            };
            }
            
            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.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_reports.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_reports',
                        'source_reference',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

