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



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

module.exports = class Asset_variantsDBApi {
    

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

        const asset_variants = await db.asset_variants.create(
            {
                id: data.id || undefined,
        
        variant_type: data.variant_type
        ||
        null
            ,
            
        cdn_url: data.cdn_url
        ||
        null
            ,
            
        width_px: data.width_px
        ||
        null
            ,
            
        height_px: data.height_px
        ||
        null
            ,
            
        size_mb: data.size_mb
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await asset_variants.setAsset( data.asset || null, {
            transaction,
        });
        

        

        

        return asset_variants;
    }
    

    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 asset_variantsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                variant_type: item.variant_type
            ||
            null
            ,
            
                cdn_url: item.cdn_url
            ||
            null
            ,
            
                width_px: item.width_px
            ||
            null
            ,
            
                height_px: item.height_px
            ||
            null
            ,
            
                size_mb: item.size_mb
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return asset_variants;
    }

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

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


        

        const updatePayload = {};
        
        if (data.variant_type !== undefined) updatePayload.variant_type = data.variant_type;
        
        
        if (data.cdn_url !== undefined) updatePayload.cdn_url = data.cdn_url;
        
        
        if (data.width_px !== undefined) updatePayload.width_px = data.width_px;
        
        
        if (data.height_px !== undefined) updatePayload.height_px = data.height_px;
        
        
        if (data.size_mb !== undefined) updatePayload.size_mb = data.size_mb;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.asset !== undefined) {
            await asset_variants.setAsset(
              
              data.asset,
              
              { transaction }
            );
        }
        

        
        

        

        return asset_variants;
    }

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

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

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


        return asset_variants;
    }

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

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

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

        await asset_variants.destroy({
            transaction
        });

        return asset_variants;
    }

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

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

        if (!asset_variants) {
            return asset_variants;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.asset = await asset_variants.getAsset({
            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.assets,
        as: 'asset',
        
        where: filter.asset ? {
          [Op.or]: [
            { id: { [Op.in]: filter.asset.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.asset.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.cdn_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'asset_variants',
                        'cdn_url',
                        filter.cdn_url,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};
