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

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

        const restaurant_tables = await db.restaurant_tables.create(
            {
                id: data.id || undefined,
        
        table_label: data.table_label
        ||
        null
            ,
            
        seat_count: data.seat_count
        ||
        null
            ,
            
        qr_payload: data.qr_payload
        ||
        null
            ,
            
        is_available: data.is_available
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await restaurant_tables.setRestaurant( data.restaurant || null, {
            transaction,
        });
        

        

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

        return restaurant_tables;
    }
    

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

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

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

        return restaurant_tables;
    }

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

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


        

        const updatePayload = {};
        
        if (data.table_label !== undefined) updatePayload.table_label = data.table_label;
        
        
        if (data.seat_count !== undefined) updatePayload.seat_count = data.seat_count;
        
        
        if (data.qr_payload !== undefined) updatePayload.qr_payload = data.qr_payload;
        
        
        if (data.is_available !== undefined) updatePayload.is_available = data.is_available;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.restaurant !== undefined) {
            await restaurant_tables.setRestaurant(
              
              data.restaurant,
              
              { transaction }
            );
        }
        

        
        

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

        return restaurant_tables;
    }

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

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

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


        return restaurant_tables;
    }

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

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

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

        await restaurant_tables.destroy({
            transaction
        });

        return restaurant_tables;
    }

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

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

        if (!restaurant_tables) {
            return restaurant_tables;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.orders_table = await restaurant_tables.getOrders_table({
            transaction
        });
        
        
        
        output.reservations_table = await restaurant_tables.getReservations_table({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.restaurant = await restaurant_tables.getRestaurant({
            transaction
        });
        
        
        output.qr_image = await restaurant_tables.getQr_image({
            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.restaurants,
        as: 'restaurant',
        
        where: filter.restaurant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.restaurant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.restaurant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.table_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'restaurant_tables',
                        'table_label',
                        filter.table_label,
                    ),
                };
            }
            
            if (filter.qr_payload) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'restaurant_tables',
                        'qr_payload',
                        filter.qr_payload,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.is_available) {
                where = {
                    ...where,
                is_available: filter.is_available,
            };
            }
            


      



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

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

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

    
};

