
const db = require('../models');
const Utils = require('../utils');
const { createBadRequestError, getCurrentOrganizationId, normalizeInventoryImportRow, loadPropertyContext, loadUnitTypeContext, prefixImportError, resolvePropertyReference, resolveUnitTypeReference } = require('./inventoryContext');

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 globalAccess = currentUser.app_role?.globalAccess;

        let propertyId = data.property || null;
        const unitType = await loadUnitTypeContext(data.unit_type || null, transaction);
        if (!propertyId && unitType?.propertyId) {
            propertyId = unitType.propertyId;
        }

        if (!propertyId) {
            throw createBadRequestError('Select a property before creating a unit.');
        }
        if (!data.unit_type) {
            throw createBadRequestError('Select a unit type before creating a unit.');
        }

        const property = await loadPropertyContext(propertyId || null, transaction);

        if (property && unitType?.propertyId && unitType.propertyId !== property.id) {
            throw createBadRequestError('Selected unit type does not belong to the selected property.');
        }

        let organizationId = data.organizations || property?.organizationsId || unitType?.organizationsId || null;
        if (!organizationId && !globalAccess) {
            organizationId = getCurrentOrganizationId(currentUser);
        }

        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( propertyId || null, {
            transaction,
        });
        
        await units.setUnit_type( data.unit_type || null, {
            transaction,
        });
        
        await units.setOrganizations( organizationId || 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;
        const seenIds = new Set();
        const seenImportHashes = new Set();
        const createdRecords = [];

        for (let index = 0; index < data.length; index += 1) {
            const item = normalizeInventoryImportRow(data[index]);
            const rowNumber = index + 2;

            try {
                const propertyId = await resolvePropertyReference(item.property, {
                    currentUser,
                    transaction,
                });

                if (!propertyId) {
                    throw createBadRequestError('Property is required for unit import.');
                }

                const property = await loadPropertyContext(propertyId, transaction);
                const unitTypeId = await resolveUnitTypeReference(item.unit_type, {
                    currentUser,
                    organizationId: property?.organizationsId || null,
                    propertyId,
                    transaction,
                });

                if (!unitTypeId) {
                    throw createBadRequestError('Unit type is required for unit import.');
                }

                item.property = propertyId;
                item.unit_type = unitTypeId;

                const itemId = item.id || null;
                const importHash = item.importHash || null;
                if (options?.ignoreDuplicates) {
                    if ((itemId && seenIds.has(itemId)) || (importHash && seenImportHashes.has(importHash))) {
                        continue;
                    }

                    const duplicateFilters = [];
                    if (itemId) {
                        duplicateFilters.push({ id: itemId });
                    }
                    if (importHash) {
                        duplicateFilters.push({ importHash });
                    }

                    if (duplicateFilters.length) {
                        const existingRecord = await db.units.findOne({
                            where: {
                                [Op.or]: duplicateFilters,
                            },
                            transaction,
                            paranoid: false,
                        });

                        if (existingRecord) {
                            continue;
                        }
                    }
                }

                if (itemId) {
                    seenIds.add(itemId);
                }
                if (importHash) {
                    seenImportHashes.add(importHash);
                }

                const createdRecord = await this.create(item, {
                    ...options,
                    currentUser,
                    transaction,
                });

                createdRecords.push(createdRecord);
            } catch (error) {
                throw prefixImportError(error, rowNumber);
            }
        }

        return createdRecords;
    }

    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 nextPropertyId = data.property !== undefined ? data.property : units?.propertyId;
        const nextUnitTypeId = data.unit_type !== undefined ? data.unit_type : units?.unit_typeId;
        const unitType = await loadUnitTypeContext(nextUnitTypeId || null, transaction);
        const propertyId = nextPropertyId || unitType?.propertyId || null;
        if (!propertyId) {
            throw createBadRequestError('Select a property before saving this unit.');
        }
        if (!nextUnitTypeId) {
            throw createBadRequestError('Select a unit type before saving this unit.');
        }

        const property = await loadPropertyContext(propertyId || null, transaction);

        if (property && unitType?.propertyId && unitType.propertyId !== property.id) {
            throw createBadRequestError('Selected unit type does not belong to the selected property.');
        }

        let organizationId = data.organizations;
        if (organizationId === undefined && (data.property !== undefined || data.unit_type !== undefined)) {
            organizationId = property?.organizationsId || unitType?.organizationsId || null;
        }
        if ((organizationId === undefined || organizationId === null) && !globalAccess && !units?.organizationsId) {
            organizationId = getCurrentOrganizationId(currentUser);
        }

        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 || (data.unit_type !== undefined && propertyId !== units?.propertyId)) {
            await units.setProperty(
              
              propertyId,
              
              { transaction }
            );
        }
        
        if (data.unit_type !== undefined) {
            await units.setUnit_type(
              
              data.unit_type,
              
              { transaction }
            );
        }
        
        if (organizationId !== undefined) {
            await units.setOrganizations(
              
              organizationId,
              
              { 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;


    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, propertyId, unitTypeId) {
        const filters = [];
        
        if (!globalAccess && organizationId) {
            filters.push({ organizationsId: organizationId });
        }
        
        if (propertyId) {
            filters.push({ propertyId: Utils.uuid(propertyId) });
        }

        if (unitTypeId) {
            filters.push({ unit_typeId: Utils.uuid(unitTypeId) });
        }

        if (query) {
            filters.push({
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'units',
                        'unit_number',
                        query,
                    ),
                ],
            });
        }

        const where = filters.length > 1
            ? { [Op.and]: filters }
            : (filters[0] || {});

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

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

    
};

