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

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

        const release_deliveries = await db.release_deliveries.create(
            {
                id: data.id || undefined,
        
        delivery_status: data.delivery_status
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        sent_at: data.sent_at
        ||
        null
            ,
            
        delivered_at: data.delivered_at
        ||
        null
            ,
            
        platform_release_url: data.platform_release_url
        ||
        null
            ,
            
        external_reference: data.external_reference
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return release_deliveries;
    }
    

    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 release_deliveriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                delivery_status: item.delivery_status
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                sent_at: item.sent_at
            ||
            null
            ,
            
                delivered_at: item.delivered_at
            ||
            null
            ,
            
                platform_release_url: item.platform_release_url
            ||
            null
            ,
            
                external_reference: item.external_reference
            ||
            null
            ,
            
                error_message: item.error_message
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return release_deliveries;
    }

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


        

        const updatePayload = {};
        
        if (data.delivery_status !== undefined) updatePayload.delivery_status = data.delivery_status;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
        
        
        if (data.delivered_at !== undefined) updatePayload.delivered_at = data.delivered_at;
        
        
        if (data.platform_release_url !== undefined) updatePayload.platform_release_url = data.platform_release_url;
        
        
        if (data.external_reference !== undefined) updatePayload.external_reference = data.external_reference;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return release_deliveries;
    }

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

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

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


        return release_deliveries;
    }

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

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

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

        await release_deliveries.destroy({
            transaction
        });

        return release_deliveries;
    }

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

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

        if (!release_deliveries) {
            return release_deliveries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.release = await release_deliveries.getRelease({
            transaction
        });
        
        
        output.platform = await release_deliveries.getPlatform({
            transaction
        });
        
        
        output.organizations = await release_deliveries.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.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.platform_release_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'release_deliveries',
                        'platform_release_url',
                        filter.platform_release_url,
                    ),
                };
            }
            
            if (filter.external_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'release_deliveries',
                        'external_reference',
                        filter.external_reference,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'release_deliveries',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.delivery_status) {
                where = {
                    ...where,
                delivery_status: filter.delivery_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.release_deliveries.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(
                        'release_deliveries',
                        'delivery_status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

