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

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

        const brands = await db.brands.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        tagline: data.tagline
        ||
        null
            ,
            
        primary_color: data.primary_color
        ||
        null
            ,
            
        secondary_color: data.secondary_color
        ||
        null
            ,
            
        support_email: data.support_email
        ||
        null
            ,
            
        support_phone: data.support_phone
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return brands;
    }
    

    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 brandsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                tagline: item.tagline
            ||
            null
            ,
            
                primary_color: item.primary_color
            ||
            null
            ,
            
                secondary_color: item.secondary_color
            ||
            null
            ,
            
                support_email: item.support_email
            ||
            null
            ,
            
                support_phone: item.support_phone
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return brands;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.tagline !== undefined) updatePayload.tagline = data.tagline;
        
        
        if (data.primary_color !== undefined) updatePayload.primary_color = data.primary_color;
        
        
        if (data.secondary_color !== undefined) updatePayload.secondary_color = data.secondary_color;
        
        
        if (data.support_email !== undefined) updatePayload.support_email = data.support_email;
        
        
        if (data.support_phone !== undefined) updatePayload.support_phone = data.support_phone;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return brands;
    }

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

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

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


        return brands;
    }

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

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

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

        await brands.destroy({
            transaction
        });

        return brands;
    }

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

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

        if (!brands) {
            return brands;
        }

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

        
        
        
        
        
        
        output.products_brand = await brands.getProducts_brand({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.logo_images = await brands.getLogo_images({
            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;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [



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

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brands',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.tagline) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brands',
                        'tagline',
                        filter.tagline,
                    ),
                };
            }
            
            if (filter.primary_color) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brands',
                        'primary_color',
                        filter.primary_color,
                    ),
                };
            }
            
            if (filter.secondary_color) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brands',
                        'secondary_color',
                        filter.secondary_color,
                    ),
                };
            }
            
            if (filter.support_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brands',
                        'support_email',
                        filter.support_email,
                    ),
                };
            }
            
            if (filter.support_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brands',
                        'support_phone',
                        filter.support_phone,
                    ),
                };
            }
            

            
            

            

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

            




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

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

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

    
};

