
const db = require('../models');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Pwa_cachesDBApi {
    

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

        const pwa_caches = await db.pwa_caches.create(
            {
                id: data.id || undefined,
        
        environment: data.environment
        ||
        null
            ,
            
        cache_version: data.cache_version
        ||
        null
            ,
            
        manifest_json: data.manifest_json
        ||
        null
            ,
            
        asset_list_json: data.asset_list_json
        ||
        null
            ,
            
        generated_at: data.generated_at
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await pwa_caches.setProject( data.project || null, {
            transaction,
        });
        

        

        

        return pwa_caches;
    }
    

    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 pwa_cachesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                environment: item.environment
            ||
            null
            ,
            
                cache_version: item.cache_version
            ||
            null
            ,
            
                manifest_json: item.manifest_json
            ||
            null
            ,
            
                asset_list_json: item.asset_list_json
            ||
            null
            ,
            
                generated_at: item.generated_at
            ||
            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 pwa_caches = await db.pwa_caches.bulkCreate(pwa_cachesData, { transaction });

        // For each item created, replace relation files
        

        return pwa_caches;
    }

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

        const pwa_caches = await db.pwa_caches.findByPk(id, {transaction});


        

        const updatePayload = {};
        
        if (data.environment !== undefined) updatePayload.environment = data.environment;
        
        
        if (data.cache_version !== undefined) updatePayload.cache_version = data.cache_version;
        
        
        if (data.manifest_json !== undefined) updatePayload.manifest_json = data.manifest_json;
        
        
        if (data.asset_list_json !== undefined) updatePayload.asset_list_json = data.asset_list_json;
        
        
        if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await pwa_caches.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        

        
        

        

        return pwa_caches;
    }

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

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

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


        return pwa_caches;
    }

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

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

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

        await pwa_caches.destroy({
            transaction
        });

        return pwa_caches;
    }

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

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

        if (!pwa_caches) {
            return pwa_caches;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.project = await pwa_caches.getProject({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

    let include = [

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



    ];

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

            
            if (filter.cache_version) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pwa_caches',
                        'cache_version',
                        filter.cache_version,
                    ),
                };
            }
            
            if (filter.manifest_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pwa_caches',
                        'manifest_json',
                        filter.manifest_json,
                    ),
                };
            }
            
            if (filter.asset_list_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pwa_caches',
                        'asset_list_json',
                        filter.asset_list_json,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.pwa_caches.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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'pwa_caches',
                        'cache_version',
                        query,
                    ),
                ],
            };
        }

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

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

    
};
