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

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

        const lead_photos = await db.lead_photos.create(
            {
                id: data.id || undefined,
        
        created_at_ts: data.created_at_ts
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await lead_photos.setLead( data.lead || null, {
            transaction,
        });
        

        

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

        return lead_photos;
    }
    

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

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

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

        return lead_photos;
    }

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

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


        

        const updatePayload = {};
        
        if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.lead !== undefined) {
            await lead_photos.setLead(
              
              data.lead,
              
              { transaction }
            );
        }
        

        
        

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

        return lead_photos;
    }

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

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

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


        return lead_photos;
    }

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

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

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

        await lead_photos.destroy({
            transaction
        });

        return lead_photos;
    }

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

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

        if (!lead_photos) {
            return lead_photos;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.lead = await lead_photos.getLead({
            transaction
        });
        
        
        output.photos = await lead_photos.getPhotos({
            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.leads,
        as: 'lead',
        
        where: filter.lead ? {
          [Op.or]: [
            { id: { [Op.in]: filter.lead.split('|').map(term => Utils.uuid(term)) } },
            {
              keyword: {
                [Op.or]: filter.lead.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            

            
            

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

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

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

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

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

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

    
};

