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

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

        const tenants = await db.tenants.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        legal_name: data.legal_name
        ||
        null
            ,
            
        primary_domain: data.primary_domain
        ||
        null
            ,
            
        timezone: data.timezone
        ||
        null
            ,
            
        default_currency: data.default_currency
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        
        await tenants.setOrganizations(data.organizations || [], {
            transaction,
        });
        
        await tenants.setProperties(data.properties || [], {
            transaction,
        });
        
        await tenants.setAudit_logs(data.audit_logs || [], {
            transaction,
        });
        

        

        return tenants;
    }
    

    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 tenantsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                legal_name: item.legal_name
            ||
            null
            ,
            
                primary_domain: item.primary_domain
            ||
            null
            ,
            
                timezone: item.timezone
            ||
            null
            ,
            
                default_currency: item.default_currency
            ||
            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 tenants = await db.tenants.bulkCreate(tenantsData, { transaction });

        // For each item created, replace relation files
        

        return tenants;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
        
        
        if (data.primary_domain !== undefined) updatePayload.primary_domain = data.primary_domain;
        
        
        if (data.timezone !== undefined) updatePayload.timezone = data.timezone;
        
        
        if (data.default_currency !== undefined) updatePayload.default_currency = data.default_currency;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        
        if (data.organizations !== undefined) {
            await tenants.setOrganizations(data.organizations, { transaction });
        }
        
        if (data.properties !== undefined) {
            await tenants.setProperties(data.properties, { transaction });
        }
        
        if (data.audit_logs !== undefined) {
            await tenants.setAudit_logs(data.audit_logs, { transaction });
        }
        

        

        return tenants;
    }

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

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

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


        return tenants;
    }

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

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

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

        await tenants.destroy({
            transaction
        });

        return tenants;
    }

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

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

        if (!tenants) {
            return tenants;
        }

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

        
        
        
        
        
        
        output.role_assignments_tenant = await tenants.getRole_assignments_tenant({
            transaction
        });
        
        
        
        output.properties_tenant = await tenants.getProperties_tenant({
            transaction
        });
        
        
        
        
        
        
        
        output.booking_requests_tenant = await tenants.getBooking_requests_tenant({
            transaction
        });
        
        
        
        
        output.reservations_tenant = await tenants.getReservations_tenant({
            transaction
        });
        
        
        
        output.service_requests_tenant = await tenants.getService_requests_tenant({
            transaction
        });
        
        
        output.invoices_tenant = await tenants.getInvoices_tenant({
            transaction
        });
        
        
        
        
        output.documents_tenant = await tenants.getDocuments_tenant({
            transaction
        });
        
        
        output.audit_logs_tenant = await tenants.getAudit_logs_tenant({
            transaction
        });
        
        
        output.notifications_tenant = await tenants.getNotifications_tenant({
            transaction
        });
        
        
        output.activity_comments_tenant = await tenants.getActivity_comments_tenant({
            transaction
        });
        
        
        output.checklists_tenant = await tenants.getChecklists_tenant({
            transaction
        });
        
        
        
        output.job_runs_tenant = await tenants.getJob_runs_tenant({
            transaction
        });
        
        
        
        output.organizations = await tenants.getOrganizations({
            transaction
        });
        
        
        output.properties = await tenants.getProperties({
            transaction
        });
        
        
        output.audit_logs = await tenants.getAudit_logs({
            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.organizations,
        as: 'organizations',
        required: false,
      },

      {
        model: db.properties,
        as: 'properties',
        required: false,
      },

      {
        model: db.audit_logs,
        as: 'audit_logs',
        required: false,
      },


    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.legal_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'legal_name',
                        filter.legal_name,
                    ),
                };
            }
            
            if (filter.primary_domain) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'primary_domain',
                        filter.primary_domain,
                    ),
                };
            }
            
            if (filter.timezone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'timezone',
                        filter.timezone,
                    ),
                };
            }
            
            if (filter.default_currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenants',
                        'default_currency',
                        filter.default_currency,
                    ),
                };
            }
            

            
            

            

            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 searchTerms = filter.organizations.split('|');

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

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

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

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

        include = [
          {
            model: db.audit_logs,
            as: 'audit_logs_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  action: {
                    [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.tenants.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(
                        'tenants',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

    
};

