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

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

        const tenders = await db.tenders.create(
            {
                id: data.id || undefined,
        
        tender_number: data.tender_number
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        tender_type: data.tender_type
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
        closing_at: data.closing_at
        ||
        null
            ,
            
        opening_at: data.opening_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        eligibility_criteria: data.eligibility_criteria
        ||
        null
            ,
            
        submission_instructions: data.submission_instructions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await tenders.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await tenders.setRequisition( data.requisition || null, {
            transaction,
        });
        

        

        

        return tenders;
    }
    

    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 tendersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                tender_number: item.tender_number
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                tender_type: item.tender_type
            ||
            null
            ,
            
                published_at: item.published_at
            ||
            null
            ,
            
                closing_at: item.closing_at
            ||
            null
            ,
            
                opening_at: item.opening_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                eligibility_criteria: item.eligibility_criteria
            ||
            null
            ,
            
                submission_instructions: item.submission_instructions
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return tenders;
    }

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


        

        const updatePayload = {};
        
        if (data.tender_number !== undefined) updatePayload.tender_number = data.tender_number;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.tender_type !== undefined) updatePayload.tender_type = data.tender_type;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        if (data.closing_at !== undefined) updatePayload.closing_at = data.closing_at;
        
        
        if (data.opening_at !== undefined) updatePayload.opening_at = data.opening_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.eligibility_criteria !== undefined) updatePayload.eligibility_criteria = data.eligibility_criteria;
        
        
        if (data.submission_instructions !== undefined) updatePayload.submission_instructions = data.submission_instructions;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await tenders.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.requisition !== undefined) {
            await tenders.setRequisition(
              
              data.requisition,
              
              { transaction }
            );
        }
        

        
        

        

        return tenders;
    }

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

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

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


        return tenders;
    }

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

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

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

        await tenders.destroy({
            transaction
        });

        return tenders;
    }

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

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

        if (!tenders) {
            return tenders;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.bids_tender = await tenders.getBids_tender({
            transaction
        });
        
        
        
        output.awards_tender = await tenders.getAwards_tender({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await tenders.getOrganization({
            transaction
        });
        
        
        output.requisition = await tenders.getRequisition({
            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.requisitions,
        as: 'requisition',
        
        where: filter.requisition ? {
          [Op.or]: [
            { id: { [Op.in]: filter.requisition.split('|').map(term => Utils.uuid(term)) } },
            {
              requisition_number: {
                [Op.or]: filter.requisition.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.tender_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenders',
                        'tender_number',
                        filter.tender_number,
                    ),
                };
            }
            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenders',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.eligibility_criteria) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenders',
                        'eligibility_criteria',
                        filter.eligibility_criteria,
                    ),
                };
            }
            
            if (filter.submission_instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tenders',
                        'submission_instructions',
                        filter.submission_instructions,
                    ),
                };
            }
            

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    opening_at: {
                    ...where.opening_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.tender_type) {
                where = {
                    ...where,
                tender_type: filter.tender_type,
            };
            }
            
            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.tenders.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(
                        'tenders',
                        'tender_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

