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

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

        const restaurants = await db.restaurants.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        contact_phone: data.contact_phone
        ||
        null
            ,
            
        staff_count_planned: data.staff_count_planned
        ||
        null
            ,
            
        table_count: data.table_count
        ||
        null
            ,
            
        opening_time: data.opening_time
        ||
        null
            ,
            
        closing_time: data.closing_time
        ||
        null
            ,
            
        latitude: data.latitude
        ||
        null
            ,
            
        longitude: data.longitude
        ||
        null
            ,
            
        geofence_radius_meters: data.geofence_radius_meters
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return restaurants;
    }
    

    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 restaurantsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                contact_phone: item.contact_phone
            ||
            null
            ,
            
                staff_count_planned: item.staff_count_planned
            ||
            null
            ,
            
                table_count: item.table_count
            ||
            null
            ,
            
                opening_time: item.opening_time
            ||
            null
            ,
            
                closing_time: item.closing_time
            ||
            null
            ,
            
                latitude: item.latitude
            ||
            null
            ,
            
                longitude: item.longitude
            ||
            null
            ,
            
                geofence_radius_meters: item.geofence_radius_meters
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return restaurants;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
        
        
        if (data.staff_count_planned !== undefined) updatePayload.staff_count_planned = data.staff_count_planned;
        
        
        if (data.table_count !== undefined) updatePayload.table_count = data.table_count;
        
        
        if (data.opening_time !== undefined) updatePayload.opening_time = data.opening_time;
        
        
        if (data.closing_time !== undefined) updatePayload.closing_time = data.closing_time;
        
        
        if (data.latitude !== undefined) updatePayload.latitude = data.latitude;
        
        
        if (data.longitude !== undefined) updatePayload.longitude = data.longitude;
        
        
        if (data.geofence_radius_meters !== undefined) updatePayload.geofence_radius_meters = data.geofence_radius_meters;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return restaurants;
    }

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

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

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


        return restaurants;
    }

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

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

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

        await restaurants.destroy({
            transaction
        });

        return restaurants;
    }

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

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

        if (!restaurants) {
            return restaurants;
        }

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

        
        
        
        
        
        
        output.restaurant_tables_restaurant = await restaurants.getRestaurant_tables_restaurant({
            transaction
        });
        
        
        output.work_schedules_restaurant = await restaurants.getWork_schedules_restaurant({
            transaction
        });
        
        
        
        output.attendance_events_restaurant = await restaurants.getAttendance_events_restaurant({
            transaction
        });
        
        
        output.geofence_alerts_restaurant = await restaurants.getGeofence_alerts_restaurant({
            transaction
        });
        
        
        output.menu_categories_restaurant = await restaurants.getMenu_categories_restaurant({
            transaction
        });
        
        
        output.menu_items_restaurant = await restaurants.getMenu_items_restaurant({
            transaction
        });
        
        
        output.orders_restaurant = await restaurants.getOrders_restaurant({
            transaction
        });
        
        
        
        output.reservations_restaurant = await restaurants.getReservations_restaurant({
            transaction
        });
        
        
        output.payments_restaurant = await restaurants.getPayments_restaurant({
            transaction
        });
        
        
        
        
        
        output.customer_reviews_restaurant = await restaurants.getCustomer_reviews_restaurant({
            transaction
        });
        
        
        output.notification_events_restaurant = await restaurants.getNotification_events_restaurant({
            transaction
        });
        
        
        output.stock_locations_restaurant = await restaurants.getStock_locations_restaurant({
            transaction
        });
        
        
        
        output.stock_movements_restaurant = await restaurants.getStock_movements_restaurant({
            transaction
        });
        
        
        output.invoices_restaurant = await restaurants.getInvoices_restaurant({
            transaction
        });
        
        
        output.audit_logs_restaurant = await restaurants.getAudit_logs_restaurant({
            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 = [



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'restaurants',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'restaurants',
                        'address',
                        filter.address,
                    ),
                };
            }
            
            if (filter.contact_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'restaurants',
                        'contact_phone',
                        filter.contact_phone,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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




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

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

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

    
};

