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

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

        const proposals = await db.proposals.create(
            {
                id: data.id || undefined,
        
        cover_letter: data.cover_letter
        ||
        null
            ,
            
        proposed_amount: data.proposed_amount
        ||
        null
            ,
            
        pricing_model: data.pricing_model
        ||
        null
            ,
            
        estimated_days: data.estimated_days
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        responded_at: data.responded_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await proposals.setJob( data.job || null, {
            transaction,
        });
        
        await proposals.setFreelancer( data.freelancer || null, {
            transaction,
        });
        

        

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

        return proposals;
    }
    

    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 proposalsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                cover_letter: item.cover_letter
            ||
            null
            ,
            
                proposed_amount: item.proposed_amount
            ||
            null
            ,
            
                pricing_model: item.pricing_model
            ||
            null
            ,
            
                estimated_days: item.estimated_days
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                responded_at: item.responded_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return proposals;
    }

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

        const proposals = await db.proposals.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.cover_letter !== undefined) updatePayload.cover_letter = data.cover_letter;
        
        
        if (data.proposed_amount !== undefined) updatePayload.proposed_amount = data.proposed_amount;
        
        
        if (data.pricing_model !== undefined) updatePayload.pricing_model = data.pricing_model;
        
        
        if (data.estimated_days !== undefined) updatePayload.estimated_days = data.estimated_days;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.responded_at !== undefined) updatePayload.responded_at = data.responded_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.job !== undefined) {
            await proposals.setJob(
              
              data.job,
              
              { transaction }
            );
        }
        
        if (data.freelancer !== undefined) {
            await proposals.setFreelancer(
              
              data.freelancer,
              
              { transaction }
            );
        }
        

        
        

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

        return proposals;
    }

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

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

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


        return proposals;
    }

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

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

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

        await proposals.destroy({
            transaction
        });

        return proposals;
    }

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

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

        if (!proposals) {
            return proposals;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.contracts_proposal = await proposals.getContracts_proposal({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.job = await proposals.getJob({
            transaction
        });
        
        
        output.freelancer = await proposals.getFreelancer({
            transaction
        });
        
        
        output.sample_files = await proposals.getSample_files({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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



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

    ];

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

            
            if (filter.cover_letter) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'proposals',
                        'cover_letter',
                        filter.cover_letter,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.pricing_model) {
                where = {
                    ...where,
                pricing_model: filter.pricing_model,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.proposals.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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'proposals',
                        'cover_letter',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

