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

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

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

        
        await place_feature_links.setPlace( data.place || null, {
            transaction,
        });
        
        await place_feature_links.setFeature( data.feature || null, {
            transaction,
        });
        

        

        

        return place_feature_links;
    }
    

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

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

        // For each item created, replace relation files
        

        return place_feature_links;
    }

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

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


        

        const updatePayload = {};
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.place !== undefined) {
            await place_feature_links.setPlace(
              
              data.place,
              
              { transaction }
            );
        }
        
        if (data.feature !== undefined) {
            await place_feature_links.setFeature(
              
              data.feature,
              
              { transaction }
            );
        }
        

        
        

        

        return place_feature_links;
    }

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

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

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


        return place_feature_links;
    }

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

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

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

        await place_feature_links.destroy({
            transaction
        });

        return place_feature_links;
    }

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

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

        if (!place_feature_links) {
            return place_feature_links;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.place = await place_feature_links.getPlace({
            transaction
        });
        
        
        output.feature = await place_feature_links.getFeature({
            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.places,
        as: 'place',
        
        where: filter.place ? {
          [Op.or]: [
            { id: { [Op.in]: filter.place.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.place.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.place_features,
        as: 'feature',
        
        where: filter.feature ? {
          [Op.or]: [
            { id: { [Op.in]: filter.feature.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.feature.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

            
            

            

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

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

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

    
};

