
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,
        
        status: data.status
        ||
        null
            ,
            
        agreed_amount: data.agreed_amount
        ||
        null
            ,
            
        pricing_model: data.pricing_model
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        terms: data.terms
        ||
        null
            ,
            
        revision_limit: data.revision_limit
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await contracts.setJob( data.job || null, {
            transaction,
        });
        
        await contracts.setProposal( data.proposal || null, {
            transaction,
        });
        
        await contracts.setClient( data.client || null, {
            transaction,
        });
        
        await contracts.setFreelancer( data.freelancer || 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,
                
                status: item.status
            ||
            null
            ,
            
                agreed_amount: item.agreed_amount
            ||
            null
            ,
            
                pricing_model: item.pricing_model
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
                terms: item.terms
            ||
            null
            ,
            
                revision_limit: item.revision_limit
            ||
            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 contracts = await db.contracts.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.agreed_amount !== undefined) updatePayload.agreed_amount = data.agreed_amount;
        
        
        if (data.pricing_model !== undefined) updatePayload.pricing_model = data.pricing_model;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.terms !== undefined) updatePayload.terms = data.terms;
        
        
        if (data.revision_limit !== undefined) updatePayload.revision_limit = data.revision_limit;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.job !== undefined) {
            await contracts.setJob(
              
              data.job,
              
              { transaction }
            );
        }
        
        if (data.proposal !== undefined) {
            await contracts.setProposal(
              
              data.proposal,
              
              { transaction }
            );
        }
        
        if (data.client !== undefined) {
            await contracts.setClient(
              
              data.client,
              
              { transaction }
            );
        }
        
        if (data.freelancer !== undefined) {
            await contracts.setFreelancer(
              
              data.freelancer,
              
              { 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.milestones_contract = await contracts.getMilestones_contract({
            transaction
        });
        
        
        output.deliverables_contract = await contracts.getDeliverables_contract({
            transaction
        });
        
        
        output.conversations_contract = await contracts.getConversations_contract({
            transaction
        });
        
        
        
        
        output.payments_contract = await contracts.getPayments_contract({
            transaction
        });
        
        
        
        output.reviews_contract = await contracts.getReviews_contract({
            transaction
        });
        
        
        output.disputes_contract = await contracts.getDisputes_contract({
            transaction
        });
        
        
        
        
        
        
        
        output.job = await contracts.getJob({
            transaction
        });
        
        
        output.proposal = await contracts.getProposal({
            transaction
        });
        
        
        output.client = await contracts.getClient({
            transaction
        });
        
        
        output.freelancer = await contracts.getFreelancer({
            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.proposals,
        as: 'proposal',
        
        where: filter.proposal ? {
          [Op.or]: [
            { id: { [Op.in]: filter.proposal.split('|').map(term => Utils.uuid(term)) } },
            {
              cover_letter: {
                [Op.or]: filter.proposal.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'client',
        
        where: filter.client ? {
          [Op.or]: [
            { id: { [Op.in]: filter.client.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.client.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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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


      

      

      

      



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

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

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

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

    
};

