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

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

        const units = await db.units.create(
            {
                id: data.id || undefined,
        
        unit_number: data.unit_number
        ||
        null
            ,
            
        floor: data.floor
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        max_occupancy_override: data.max_occupancy_override
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await units.setProperty( data.property || null, {
            transaction,
        });
        
        await units.setUnit_type( data.unit_type || null, {
            transaction,
        });
        
        await units.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await units.setAvailability_blocks(data.availability_blocks || [], {
            transaction,
        });
        

        

        return units;
    }
    

    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 unitsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                unit_number: item.unit_number
            ||
            null
            ,
            
                floor: item.floor
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                max_occupancy_override: item.max_occupancy_override
            ||
            null
            ,
            
                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 units = await db.units.bulkCreate(unitsData, { transaction });

        // For each item created, replace relation files
        

        return units;
    }

    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 units = await db.units.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.unit_number !== undefined) updatePayload.unit_number = data.unit_number;
        
        
        if (data.floor !== undefined) updatePayload.floor = data.floor;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.max_occupancy_override !== undefined) updatePayload.max_occupancy_override = data.max_occupancy_override;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.property !== undefined) {
            await units.setProperty(
              
              data.property,
              
              { transaction }
            );
        }
        
        if (data.unit_type !== undefined) {
            await units.setUnit_type(
              
              data.unit_type,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await units.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.availability_blocks !== undefined) {
            await units.setAvailability_blocks(data.availability_blocks, { transaction });
        }
        

        

        return units;
    }

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

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

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


        return units;
    }

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

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

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

        await units.destroy({
            transaction
        });

        return units;
    }

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

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

        if (!units) {
            return units;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.unit_availability_blocks_unit = await units.getUnit_availability_blocks_unit({
            transaction
        });
        
        
        
        
        
        
        output.reservations_unit = await units.getReservations_unit({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.property = await units.getProperty({
            transaction
        });
        
        
        output.unit_type = await units.getUnit_type({
            transaction
        });
        
        
        output.availability_blocks = await units.getAvailability_blocks({
            transaction
        });
        
        
        output.organizations = await units.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.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.unit_types,
        as: 'unit_type',
        
        where: filter.unit_type ? {
          [Op.or]: [
            { id: { [Op.in]: filter.unit_type.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.unit_type.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.unit_availability_blocks,
        as: 'availability_blocks',
        required: false,
      },


    ];

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

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

            
            

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

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

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

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

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


      

      

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

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


      if (filter.availability_blocks) {
        const searchTerms = filter.availability_blocks.split('|');

        include = [
          {
            model: db.unit_availability_blocks,
            as: 'availability_blocks_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  reason: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

