
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,
        
        brand_name: data.brand_name
        ||
        null
            ,
            
        website_url: data.website_url
        ||
        null
            ,
            
        industry: data.industry
        ||
        null
            ,
            
        primary_market: data.primary_market
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.brands.getTableName(),
                belongsToColumn: 'brand_assets',
                belongsToId: brands.id,
            },
            data.brand_assets,
            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,
                
                brand_name: item.brand_name
            ||
            null
            ,
            
                website_url: item.website_url
            ||
            null
            ,
            
                industry: item.industry
            ||
            null
            ,
            
                primary_market: item.primary_market
            ||
            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: 'brand_assets',
                    belongsToId: brands[i].id,
                },
                data[i].brand_assets,
                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.brand_name !== undefined) updatePayload.brand_name = data.brand_name;
        
        
        if (data.website_url !== undefined) updatePayload.website_url = data.website_url;
        
        
        if (data.industry !== undefined) updatePayload.industry = data.industry;
        
        
        if (data.primary_market !== undefined) updatePayload.primary_market = data.primary_market;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.brands.getTableName(),
                belongsToColumn: 'brand_assets',
                belongsToId: brands.id,
            },
            data.brand_assets,
            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.brand_voice_profiles_brand = await brands.getBrand_voice_profiles_brand({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.campaigns_brand = await brands.getCampaigns_brand({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.brand_assets = await brands.getBrand_assets({
            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: 'brand_assets',
      },

    ];

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

            
            if (filter.brand_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brands',
                        'brand_name',
                        filter.brand_name,
                    ),
                };
            }
            
            if (filter.website_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brands',
                        'website_url',
                        filter.website_url,
                    ),
                };
            }
            
            if (filter.industry) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brands',
                        'industry',
                        filter.industry,
                    ),
                };
            }
            
            if (filter.primary_market) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'brands',
                        'primary_market',
                        filter.primary_market,
                    ),
                };
            }
            

            
            

            

            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',
                        'brand_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

