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

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

        const tender_events = await db.tender_events.create(
            {
                id: data.id || undefined,
        
        reference: data.reference
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
        submission_deadline: data.submission_deadline
        ||
        null
            ,
            
        opened_at: data.opened_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await tender_events.setTenant( data.tenant || null, {
            transaction,
        });
        
        await tender_events.setProcurement_case( data.procurement_case || null, {
            transaction,
        });
        
        await tender_events.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return tender_events;
    }
    

    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 tender_eventsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                reference: item.reference
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                published_at: item.published_at
            ||
            null
            ,
            
                submission_deadline: item.submission_deadline
            ||
            null
            ,
            
                opened_at: item.opened_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return tender_events;
    }

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


        

        const updatePayload = {};
        
        if (data.reference !== undefined) updatePayload.reference = data.reference;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        if (data.submission_deadline !== undefined) updatePayload.submission_deadline = data.submission_deadline;
        
        
        if (data.opened_at !== undefined) updatePayload.opened_at = data.opened_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await tender_events.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.procurement_case !== undefined) {
            await tender_events.setProcurement_case(
              
              data.procurement_case,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await tender_events.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return tender_events;
    }

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

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

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


        return tender_events;
    }

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

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

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

        await tender_events.destroy({
            transaction
        });

        return tender_events;
    }

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

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

        if (!tender_events) {
            return tender_events;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await tender_events.getTenant({
            transaction
        });
        
        
        output.procurement_case = await tender_events.getProcurement_case({
            transaction
        });
        
        
        output.tender_documents = await tender_events.getTender_documents({
            transaction
        });
        
        
        output.organizations = await tender_events.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.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.procurement_cases,
        as: 'procurement_case',
        
        where: filter.procurement_case ? {
          [Op.or]: [
            { id: { [Op.in]: filter.procurement_case.split('|').map(term => Utils.uuid(term)) } },
            {
              pipeline_stage: {
                [Op.or]: filter.procurement_case.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



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

    ];

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

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

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    opened_at: {
                    ...where.opened_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.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.tender_events.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(
                        'tender_events',
                        'reference',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

