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

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

        const contracts = await db.contracts.create(
            {
                id: data.id || undefined,
        
        contract_number: data.contract_number
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        contract_type: data.contract_type
        ||
        null
            ,
            
        contract_value: data.contract_value
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        start_date: data.start_date
        ||
        null
            ,
            
        end_date: data.end_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        retention_percent: data.retention_percent
        ||
        null
            ,
            
        penalty_rate_percent: data.penalty_rate_percent
        ||
        null
            ,
            
        signed_at: data.signed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await contracts.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await contracts.setVendor( data.vendor || null, {
            transaction,
        });
        
        await contracts.setAward( data.award || null, {
            transaction,
        });
        
        await contracts.setProject( data.project || null, {
            transaction,
        });
        
        await contracts.setBudget_line( data.budget_line || null, {
            transaction,
        });
        

        

        

        return contracts;
    }
    

    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 contractsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                contract_number: item.contract_number
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                contract_type: item.contract_type
            ||
            null
            ,
            
                contract_value: item.contract_value
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                start_date: item.start_date
            ||
            null
            ,
            
                end_date: item.end_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                retention_percent: item.retention_percent
            ||
            null
            ,
            
                penalty_rate_percent: item.penalty_rate_percent
            ||
            null
            ,
            
                signed_at: item.signed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const contracts = await db.contracts.bulkCreate(contractsData, { transaction });

        // For each item created, replace relation files
        

        return contracts;
    }

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


        

        const updatePayload = {};
        
        if (data.contract_number !== undefined) updatePayload.contract_number = data.contract_number;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.contract_type !== undefined) updatePayload.contract_type = data.contract_type;
        
        
        if (data.contract_value !== undefined) updatePayload.contract_value = data.contract_value;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.start_date !== undefined) updatePayload.start_date = data.start_date;
        
        
        if (data.end_date !== undefined) updatePayload.end_date = data.end_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.retention_percent !== undefined) updatePayload.retention_percent = data.retention_percent;
        
        
        if (data.penalty_rate_percent !== undefined) updatePayload.penalty_rate_percent = data.penalty_rate_percent;
        
        
        if (data.signed_at !== undefined) updatePayload.signed_at = data.signed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await contracts.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.vendor !== undefined) {
            await contracts.setVendor(
              
              data.vendor,
              
              { transaction }
            );
        }
        
        if (data.award !== undefined) {
            await contracts.setAward(
              
              data.award,
              
              { transaction }
            );
        }
        
        if (data.project !== undefined) {
            await contracts.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.budget_line !== undefined) {
            await contracts.setBudget_line(
              
              data.budget_line,
              
              { transaction }
            );
        }
        

        
        

        

        return contracts;
    }

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

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

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


        return contracts;
    }

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

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

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

        await contracts.destroy({
            transaction
        });

        return contracts;
    }

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

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

        if (!contracts) {
            return contracts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.contract_amendments_contract = await contracts.getContract_amendments_contract({
            transaction
        });
        
        
        output.contract_milestones_contract = await contracts.getContract_milestones_contract({
            transaction
        });
        
        
        
        
        
        
        
        
        output.invoices_contract = await contracts.getInvoices_contract({
            transaction
        });
        
        
        
        
        
        output.obligations_contract = await contracts.getObligations_contract({
            transaction
        });
        
        
        
        
        
        
        output.organization = await contracts.getOrganization({
            transaction
        });
        
        
        output.vendor = await contracts.getVendor({
            transaction
        });
        
        
        output.award = await contracts.getAward({
            transaction
        });
        
        
        output.project = await contracts.getProject({
            transaction
        });
        
        
        output.budget_line = await contracts.getBudget_line({
            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: 'organization',
        
      },

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

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

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

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



    ];

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

            
            if (filter.contract_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'contracts',
                        'contract_number',
                        filter.contract_number,
                    ),
                };
            }
            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'contracts',
                        'title',
                        filter.title,
                    ),
                };
            }
            

            
            
            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.contract_valueRange) {
                const [start, end] = filter.contract_valueRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    contract_value: {
                    ...where.contract_value,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.retention_percentRange) {
                const [start, end] = filter.retention_percentRange;

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

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

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

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


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

        where = {
          ...where,
          organizationId: {[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.contracts.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(
                        'contracts',
                        'contract_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

