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

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

        const item_costs = await db.item_costs.create(
            {
                id: data.id || undefined,
        
        material_cost: data.material_cost
        ||
        null
            ,
            
        labor_cost: data.labor_cost
        ||
        null
            ,
            
        overhead_cost: data.overhead_cost
        ||
        null
            ,
            
        standard_cost: data.standard_cost
        ||
        null
            ,
            
        effective_from: data.effective_from
        ||
        null
            ,
            
        effective_to: data.effective_to
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await item_costs.setItem( data.item || null, {
            transaction,
        });
        
        await item_costs.setPlant( data.plant || null, {
            transaction,
        });
        

        

        

        return item_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 item_costsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                material_cost: item.material_cost
            ||
            null
            ,
            
                labor_cost: item.labor_cost
            ||
            null
            ,
            
                overhead_cost: item.overhead_cost
            ||
            null
            ,
            
                standard_cost: item.standard_cost
            ||
            null
            ,
            
                effective_from: item.effective_from
            ||
            null
            ,
            
                effective_to: item.effective_to
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return item_costs;
    }

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

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


        

        const updatePayload = {};
        
        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.standard_cost !== undefined) updatePayload.standard_cost = data.standard_cost;
        
        
        if (data.effective_from !== undefined) updatePayload.effective_from = data.effective_from;
        
        
        if (data.effective_to !== undefined) updatePayload.effective_to = data.effective_to;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.item !== undefined) {
            await item_costs.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.plant !== undefined) {
            await item_costs.setPlant(
              
              data.plant,
              
              { transaction }
            );
        }
        

        
        

        

        return item_costs;
    }

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

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

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


        return item_costs;
    }

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

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

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

        await item_costs.destroy({
            transaction
        });

        return item_costs;
    }

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

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

        if (!item_costs) {
            return item_costs;
        }

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

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



    ];

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

            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    standard_cost: {
                    ...where.standard_cost,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            


      

      



            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.item_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(
                        'item_costs',
                        'standard_cost',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

