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

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

        const leases = await db.leases.create(
            {
                id: data.id || undefined,
        
        lease_number: data.lease_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        start_date: data.start_date
        ||
        null
            ,
            
        end_date: data.end_date
        ||
        null
            ,
            
        rent_amount: data.rent_amount
        ||
        null
            ,
            
        billing_cycle: data.billing_cycle
        ||
        null
            ,
            
        deposit_amount: data.deposit_amount
        ||
        null
            ,
            
        signed_at: data.signed_at
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await leases.setCompany( data.company || null, {
            transaction,
        });
        
        await leases.setAsset( data.asset || null, {
            transaction,
        });
        
        await leases.setTenant( data.tenant || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.leases.getTableName(),
                belongsToColumn: 'contract_files',
                belongsToId: leases.id,
            },
            data.contract_files,
            options,
        );
        

        return leases;
    }
    

    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 leasesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                lease_number: item.lease_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                start_date: item.start_date
            ||
            null
            ,
            
                end_date: item.end_date
            ||
            null
            ,
            
                rent_amount: item.rent_amount
            ||
            null
            ,
            
                billing_cycle: item.billing_cycle
            ||
            null
            ,
            
                deposit_amount: item.deposit_amount
            ||
            null
            ,
            
                signed_at: item.signed_at
            ||
            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 leases = await db.leases.bulkCreate(leasesData, { transaction });

        // For each item created, replace relation files
        
        for (let i = 0; i < leases.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.leases.getTableName(),
                    belongsToColumn: 'contract_files',
                    belongsToId: leases[i].id,
                },
                data[i].contract_files,
                options,
            );
        }
        

        return leases;
    }

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


        

        const updatePayload = {};
        
        if (data.lease_number !== undefined) updatePayload.lease_number = data.lease_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.start_date !== undefined) updatePayload.start_date = data.start_date;
        
        
        if (data.end_date !== undefined) updatePayload.end_date = data.end_date;
        
        
        if (data.rent_amount !== undefined) updatePayload.rent_amount = data.rent_amount;
        
        
        if (data.billing_cycle !== undefined) updatePayload.billing_cycle = data.billing_cycle;
        
        
        if (data.deposit_amount !== undefined) updatePayload.deposit_amount = data.deposit_amount;
        
        
        if (data.signed_at !== undefined) updatePayload.signed_at = data.signed_at;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await leases.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.asset !== undefined) {
            await leases.setAsset(
              
              data.asset,
              
              { transaction }
            );
        }
        
        if (data.tenant !== undefined) {
            await leases.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.leases.getTableName(),
                belongsToColumn: 'contract_files',
                belongsToId: leases.id,
            },
            data.contract_files,
            options,
        );
        

        return leases;
    }

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

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

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


        return leases;
    }

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

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

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

        await leases.destroy({
            transaction
        });

        return leases;
    }

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

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

        if (!leases) {
            return leases;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await leases.getCompany({
            transaction
        });
        
        
        output.asset = await leases.getAsset({
            transaction
        });
        
        
        output.tenant = await leases.getTenant({
            transaction
        });
        
        
        output.contract_files = await leases.getContract_files({
            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 userCompanies = (user && user.companies?.id) || null;
        

        
        if (userCompanies) {
            if (options?.currentUser?.companiesId) {
                where.companiesId = options.currentUser.companiesId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

      {
        model: db.companies,
        as: 'company',
        
      },

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

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



      {
        model: db.file,
        as: 'contract_files',
      },

    ];

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    signed_at: {
                    ...where.signed_at,
                            [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.billing_cycle) {
                where = {
                    ...where,
                billing_cycle: filter.billing_cycle,
            };
            }
            


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

        where = {
          ...where,
          companyId: {[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.companiesId;
        }
        

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

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

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

    
};

