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

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

        const production_costs = await db.production_costs.create(
            {
                id: data.id || undefined,
        
        cost_method: data.cost_method
        ||
        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
            ,
            
        calculated_at: data.calculated_at
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await production_costs.setProduction_order( data.production_order || null, {
            transaction,
        });
        
        await production_costs.setCalculated_by( data.calculated_by || null, {
            transaction,
        });
        

        

        

        return production_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 production_costsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                cost_method: item.cost_method
            ||
            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
            ,
            
                calculated_at: item.calculated_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 production_costs = await db.production_costs.bulkCreate(production_costsData, { transaction });

        // For each item created, replace relation files
        

        return production_costs;
    }

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

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


        

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

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

        
        
        if (data.production_order !== undefined) {
            await production_costs.setProduction_order(
              
              data.production_order,
              
              { transaction }
            );
        }
        
        if (data.calculated_by !== undefined) {
            await production_costs.setCalculated_by(
              
              data.calculated_by,
              
              { transaction }
            );
        }
        

        
        

        

        return production_costs;
    }

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

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

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


        return production_costs;
    }

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

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

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

        await production_costs.destroy({
            transaction
        });

        return production_costs;
    }

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

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

        if (!production_costs) {
            return production_costs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.production_order = await production_costs.getProduction_order({
            transaction
        });
        
        
        output.calculated_by = await production_costs.getCalculated_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.production_orders,
        as: 'production_order',
        
        where: filter.production_order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.production_order.split('|').map(term => Utils.uuid(term)) } },
            {
              order_number: {
                [Op.or]: filter.production_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

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

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

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

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

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


      

      



            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.production_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(
                        'production_costs',
                        'cost_method',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

