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

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

        const recurring_schedules = await db.recurring_schedules.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        frequency: data.frequency
        ||
        null
            ,
            
        interval_count: data.interval_count
        ||
        null
            ,
            
        day_of_week: data.day_of_week
        ||
        null
            ,
            
        day_of_month: data.day_of_month
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await recurring_schedules.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await recurring_schedules.setCustomer( data.customer || null, {
            transaction,
        });
        
        await recurring_schedules.setProperty( data.property || null, {
            transaction,
        });
        
        await recurring_schedules.setService_catalog_item( data.service_catalog_item || null, {
            transaction,
        });
        
        await recurring_schedules.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return recurring_schedules;
    }
    

    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 recurring_schedulesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                frequency: item.frequency
            ||
            null
            ,
            
                interval_count: item.interval_count
            ||
            null
            ,
            
                day_of_week: item.day_of_week
            ||
            null
            ,
            
                day_of_month: item.day_of_month
            ||
            null
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return recurring_schedules;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.frequency !== undefined) updatePayload.frequency = data.frequency;
        
        
        if (data.interval_count !== undefined) updatePayload.interval_count = data.interval_count;
        
        
        if (data.day_of_week !== undefined) updatePayload.day_of_week = data.day_of_week;
        
        
        if (data.day_of_month !== undefined) updatePayload.day_of_month = data.day_of_month;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workspace !== undefined) {
            await recurring_schedules.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await recurring_schedules.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.property !== undefined) {
            await recurring_schedules.setProperty(
              
              data.property,
              
              { transaction }
            );
        }
        
        if (data.service_catalog_item !== undefined) {
            await recurring_schedules.setService_catalog_item(
              
              data.service_catalog_item,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await recurring_schedules.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return recurring_schedules;
    }

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

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

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


        return recurring_schedules;
    }

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

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

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

        await recurring_schedules.destroy({
            transaction
        });

        return recurring_schedules;
    }

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

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

        if (!recurring_schedules) {
            return recurring_schedules;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.workspace = await recurring_schedules.getWorkspace({
            transaction
        });
        
        
        output.customer = await recurring_schedules.getCustomer({
            transaction
        });
        
        
        output.property = await recurring_schedules.getProperty({
            transaction
        });
        
        
        output.service_catalog_item = await recurring_schedules.getService_catalog_item({
            transaction
        });
        
        
        output.organizations = await recurring_schedules.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

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


      

      

      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.recurring_schedules.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'recurring_schedules',
                        'name',
                        query,
                    ),
                ],
            };
        }

        const records = await db.recurring_schedules.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,
        }));
    }

    
};

