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

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

        const discovery_preferences = await db.discovery_preferences.create(
            {
                id: data.id || undefined,
        
        min_age: data.min_age
        ||
        null
            ,
            
        max_age: data.max_age
        ||
        null
            ,
            
        max_distance_km: data.max_distance_km
        ||
        null
            ,
            
        min_height_cm: data.min_height_cm
        ||
        null
            ,
            
        max_height_cm: data.max_height_cm
        ||
        null
            ,
            
        dating_intention: data.dating_intention
        ||
        null
            ,
            
        preferred_gender: data.preferred_gender
        ||
        null
            ,
            
        verified_only: data.verified_only
        ||
        false
        
            ,
            
        online_only: data.online_only
        ||
        false
        
            ,
            
        advanced_filters_enabled: data.advanced_filters_enabled
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await discovery_preferences.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return discovery_preferences;
    }
    

    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 discovery_preferencesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                min_age: item.min_age
            ||
            null
            ,
            
                max_age: item.max_age
            ||
            null
            ,
            
                max_distance_km: item.max_distance_km
            ||
            null
            ,
            
                min_height_cm: item.min_height_cm
            ||
            null
            ,
            
                max_height_cm: item.max_height_cm
            ||
            null
            ,
            
                dating_intention: item.dating_intention
            ||
            null
            ,
            
                preferred_gender: item.preferred_gender
            ||
            null
            ,
            
                verified_only: item.verified_only
            ||
            false
        
            ,
            
                online_only: item.online_only
            ||
            false
        
            ,
            
                advanced_filters_enabled: item.advanced_filters_enabled
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return discovery_preferences;
    }

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

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


        

        const updatePayload = {};
        
        if (data.min_age !== undefined) updatePayload.min_age = data.min_age;
        
        
        if (data.max_age !== undefined) updatePayload.max_age = data.max_age;
        
        
        if (data.max_distance_km !== undefined) updatePayload.max_distance_km = data.max_distance_km;
        
        
        if (data.min_height_cm !== undefined) updatePayload.min_height_cm = data.min_height_cm;
        
        
        if (data.max_height_cm !== undefined) updatePayload.max_height_cm = data.max_height_cm;
        
        
        if (data.dating_intention !== undefined) updatePayload.dating_intention = data.dating_intention;
        
        
        if (data.preferred_gender !== undefined) updatePayload.preferred_gender = data.preferred_gender;
        
        
        if (data.verified_only !== undefined) updatePayload.verified_only = data.verified_only;
        
        
        if (data.online_only !== undefined) updatePayload.online_only = data.online_only;
        
        
        if (data.advanced_filters_enabled !== undefined) updatePayload.advanced_filters_enabled = data.advanced_filters_enabled;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await discovery_preferences.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return discovery_preferences;
    }

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

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

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


        return discovery_preferences;
    }

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

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

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

        await discovery_preferences.destroy({
            transaction
        });

        return discovery_preferences;
    }

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

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

        if (!discovery_preferences) {
            return discovery_preferences;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await discovery_preferences.getUser({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.dating_intention) {
                where = {
                    ...where,
                dating_intention: filter.dating_intention,
            };
            }
            
            if (filter.preferred_gender) {
                where = {
                    ...where,
                preferred_gender: filter.preferred_gender,
            };
            }
            
            if (filter.verified_only) {
                where = {
                    ...where,
                verified_only: filter.verified_only,
            };
            }
            
            if (filter.online_only) {
                where = {
                    ...where,
                online_only: filter.online_only,
            };
            }
            
            if (filter.advanced_filters_enabled) {
                where = {
                    ...where,
                advanced_filters_enabled: filter.advanced_filters_enabled,
            };
            }
            


      



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

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

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

    
};

