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

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

        const properties = await db.properties.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        address_line1: data.address_line1
        ||
        null
            ,
            
        address_line2: data.address_line2
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        state_region: data.state_region
        ||
        null
            ,
            
        postal_code: data.postal_code
        ||
        null
            ,
            
        access_instructions: data.access_instructions
        ||
        null
            ,
            
        bedrooms: data.bedrooms
        ||
        null
            ,
            
        bathrooms: data.bathrooms
        ||
        null
            ,
            
        square_feet: data.square_feet
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await properties.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await properties.setCustomer( data.customer || null, {
            transaction,
        });
        
        await properties.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return properties;
    }
    

    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 propertiesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                address_line1: item.address_line1
            ||
            null
            ,
            
                address_line2: item.address_line2
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                state_region: item.state_region
            ||
            null
            ,
            
                postal_code: item.postal_code
            ||
            null
            ,
            
                access_instructions: item.access_instructions
            ||
            null
            ,
            
                bedrooms: item.bedrooms
            ||
            null
            ,
            
                bathrooms: item.bathrooms
            ||
            null
            ,
            
                square_feet: item.square_feet
            ||
            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 properties = await db.properties.bulkCreate(propertiesData, { transaction });

        // For each item created, replace relation files
        

        return properties;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.address_line1 !== undefined) updatePayload.address_line1 = data.address_line1;
        
        
        if (data.address_line2 !== undefined) updatePayload.address_line2 = data.address_line2;
        
        
        if (data.city !== undefined) updatePayload.city = data.city;
        
        
        if (data.state_region !== undefined) updatePayload.state_region = data.state_region;
        
        
        if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
        
        
        if (data.access_instructions !== undefined) updatePayload.access_instructions = data.access_instructions;
        
        
        if (data.bedrooms !== undefined) updatePayload.bedrooms = data.bedrooms;
        
        
        if (data.bathrooms !== undefined) updatePayload.bathrooms = data.bathrooms;
        
        
        if (data.square_feet !== undefined) updatePayload.square_feet = data.square_feet;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workspace !== undefined) {
            await properties.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await properties.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await properties.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return properties;
    }

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

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

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


        return properties;
    }

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

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

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

        await properties.destroy({
            transaction
        });

        return properties;
    }

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

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

        if (!properties) {
            return properties;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.jobs_property = await properties.getJobs_property({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.estimates_property = await properties.getEstimates_property({
            transaction
        });
        
        
        
        output.recurring_schedules_property = await properties.getRecurring_schedules_property({
            transaction
        });
        
        
        
        
        
        
        
        output.workspace = await properties.getWorkspace({
            transaction
        });
        
        
        output.customer = await properties.getCustomer({
            transaction
        });
        
        
        output.organizations = await properties.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'properties',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.address_line1) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'properties',
                        'address_line1',
                        filter.address_line1,
                    ),
                };
            }
            
            if (filter.address_line2) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'properties',
                        'address_line2',
                        filter.address_line2,
                    ),
                };
            }
            
            if (filter.city) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'properties',
                        'city',
                        filter.city,
                    ),
                };
            }
            
            if (filter.state_region) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'properties',
                        'state_region',
                        filter.state_region,
                    ),
                };
            }
            
            if (filter.postal_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'properties',
                        'postal_code',
                        filter.postal_code,
                    ),
                };
            }
            
            if (filter.access_instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'properties',
                        'access_instructions',
                        filter.access_instructions,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    square_feet: {
                    ...where.square_feet,
                            [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.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.properties.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(
                        'properties',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

    
};

