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

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

        const standard_costs = await db.standard_costs.create(
            {
                id: data.id || undefined,
        
        cost_version: data.cost_version
        ||
        null
            ,
            
        effective_from: data.effective_from
        ||
        null
            ,
            
        effective_to: data.effective_to
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        material_cost: data.material_cost
        ||
        null
            ,
            
        labor_cost: data.labor_cost
        ||
        null
            ,
            
        overhead_cost: data.overhead_cost
        ||
        null
            ,
            
        subcontract_cost: data.subcontract_cost
        ||
        null
            ,
            
        total_cost: data.total_cost
        ||
        null
            ,
            
        approved_at: data.approved_at
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await standard_costs.setItem( data.item || null, {
            transaction,
        });
        
        await standard_costs.setApproved_by( data.approved_by || null, {
            transaction,
        });
        

        

        

        return standard_costs;
    }
    

    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 standard_costsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                cost_version: item.cost_version
            ||
            null
            ,
            
                effective_from: item.effective_from
            ||
            null
            ,
            
                effective_to: item.effective_to
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                material_cost: item.material_cost
            ||
            null
            ,
            
                labor_cost: item.labor_cost
            ||
            null
            ,
            
                overhead_cost: item.overhead_cost
            ||
            null
            ,
            
                subcontract_cost: item.subcontract_cost
            ||
            null
            ,
            
                total_cost: item.total_cost
            ||
            null
            ,
            
                approved_at: item.approved_at
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return standard_costs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.cost_version !== undefined) updatePayload.cost_version = data.cost_version;
        
        
        if (data.effective_from !== undefined) updatePayload.effective_from = data.effective_from;
        
        
        if (data.effective_to !== undefined) updatePayload.effective_to = data.effective_to;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.material_cost !== undefined) updatePayload.material_cost = data.material_cost;
        
        
        if (data.labor_cost !== undefined) updatePayload.labor_cost = data.labor_cost;
        
        
        if (data.overhead_cost !== undefined) updatePayload.overhead_cost = data.overhead_cost;
        
        
        if (data.subcontract_cost !== undefined) updatePayload.subcontract_cost = data.subcontract_cost;
        
        
        if (data.total_cost !== undefined) updatePayload.total_cost = data.total_cost;
        
        
        if (data.approved_at !== undefined) updatePayload.approved_at = data.approved_at;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.item !== undefined) {
            await standard_costs.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.approved_by !== undefined) {
            await standard_costs.setApproved_by(
              
              data.approved_by,
              
              { transaction }
            );
        }
        

        
        

        

        return standard_costs;
    }

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

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

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


        return standard_costs;
    }

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

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

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

        await standard_costs.destroy({
            transaction
        });

        return standard_costs;
    }

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

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

        if (!standard_costs) {
            return standard_costs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.item = await standard_costs.getItem({
            transaction
        });
        
        
        output.approved_by = await standard_costs.getApproved_by({
            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.items,
        as: 'item',
        
        where: filter.item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.cost_version) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'standard_costs',
                        'cost_version',
                        filter.cost_version,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'standard_costs',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    approved_at: {
                    ...where.approved_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.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.standard_costs.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(
                        'standard_costs',
                        'cost_version',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

