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

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

        const place_opening_hours = await db.place_opening_hours.create(
            {
                id: data.id || undefined,
        
        day_of_week: data.day_of_week
        ||
        null
            ,
            
        open_time: data.open_time
        ||
        null
            ,
            
        close_time: data.close_time
        ||
        null
            ,
            
        is_closed: data.is_closed
        ||
        false
        
            ,
            
        is_24_hours: data.is_24_hours
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await place_opening_hours.setPlace( data.place || null, {
            transaction,
        });
        

        

        

        return place_opening_hours;
    }
    

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

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

        // For each item created, replace relation files
        

        return place_opening_hours;
    }

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

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


        

        const updatePayload = {};
        
        if (data.day_of_week !== undefined) updatePayload.day_of_week = data.day_of_week;
        
        
        if (data.open_time !== undefined) updatePayload.open_time = data.open_time;
        
        
        if (data.close_time !== undefined) updatePayload.close_time = data.close_time;
        
        
        if (data.is_closed !== undefined) updatePayload.is_closed = data.is_closed;
        
        
        if (data.is_24_hours !== undefined) updatePayload.is_24_hours = data.is_24_hours;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return place_opening_hours;
    }

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

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

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


        return place_opening_hours;
    }

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

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

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

        await place_opening_hours.destroy({
            transaction
        });

        return place_opening_hours;
    }

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

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

        if (!place_opening_hours) {
            return place_opening_hours;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.place = await place_opening_hours.getPlace({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.open_time) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'place_opening_hours',
                        'open_time',
                        filter.open_time,
                    ),
                };
            }
            
            if (filter.close_time) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'place_opening_hours',
                        'close_time',
                        filter.close_time,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.day_of_week) {
                where = {
                    ...where,
                day_of_week: filter.day_of_week,
            };
            }
            
            if (filter.is_closed) {
                where = {
                    ...where,
                is_closed: filter.is_closed,
            };
            }
            
            if (filter.is_24_hours) {
                where = {
                    ...where,
                is_24_hours: filter.is_24_hours,
            };
            }
            


      



            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_opening_hours.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_opening_hours',
                        'open_time',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

