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

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

        const repair_orders = await db.repair_orders.create(
            {
                id: data.id || undefined,
        
        order_number: data.order_number
        ||
        null
            ,
            
        source: data.source
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        problem_description: data.problem_description
        ||
        null
            ,
            
        diagnosis_notes: data.diagnosis_notes
        ||
        null
            ,
            
        internal_notes: data.internal_notes
        ||
        null
            ,
            
        estimated_cost: data.estimated_cost
        ||
        null
            ,
            
        final_cost: data.final_cost
        ||
        null
            ,
            
        requires_deposit: data.requires_deposit
        ||
        false
        
            ,
            
        deposit_amount: data.deposit_amount
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        received_at: data.received_at
        ||
        null
            ,
            
        estimated_ready_at: data.estimated_ready_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        delivered_at: data.delivered_at
        ||
        null
            ,
            
        whatsapp_notified: data.whatsapp_notified
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await repair_orders.setCustomer( data.customer || null, {
            transaction,
        });
        
        await repair_orders.setDevice( data.device || null, {
            transaction,
        });
        

        

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

        return repair_orders;
    }
    

    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 repair_ordersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                order_number: item.order_number
            ||
            null
            ,
            
                source: item.source
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                problem_description: item.problem_description
            ||
            null
            ,
            
                diagnosis_notes: item.diagnosis_notes
            ||
            null
            ,
            
                internal_notes: item.internal_notes
            ||
            null
            ,
            
                estimated_cost: item.estimated_cost
            ||
            null
            ,
            
                final_cost: item.final_cost
            ||
            null
            ,
            
                requires_deposit: item.requires_deposit
            ||
            false
        
            ,
            
                deposit_amount: item.deposit_amount
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                received_at: item.received_at
            ||
            null
            ,
            
                estimated_ready_at: item.estimated_ready_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
                delivered_at: item.delivered_at
            ||
            null
            ,
            
                whatsapp_notified: item.whatsapp_notified
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return repair_orders;
    }

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

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


        

        const updatePayload = {};
        
        if (data.order_number !== undefined) updatePayload.order_number = data.order_number;
        
        
        if (data.source !== undefined) updatePayload.source = data.source;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.problem_description !== undefined) updatePayload.problem_description = data.problem_description;
        
        
        if (data.diagnosis_notes !== undefined) updatePayload.diagnosis_notes = data.diagnosis_notes;
        
        
        if (data.internal_notes !== undefined) updatePayload.internal_notes = data.internal_notes;
        
        
        if (data.estimated_cost !== undefined) updatePayload.estimated_cost = data.estimated_cost;
        
        
        if (data.final_cost !== undefined) updatePayload.final_cost = data.final_cost;
        
        
        if (data.requires_deposit !== undefined) updatePayload.requires_deposit = data.requires_deposit;
        
        
        if (data.deposit_amount !== undefined) updatePayload.deposit_amount = data.deposit_amount;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
        
        
        if (data.estimated_ready_at !== undefined) updatePayload.estimated_ready_at = data.estimated_ready_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.delivered_at !== undefined) updatePayload.delivered_at = data.delivered_at;
        
        
        if (data.whatsapp_notified !== undefined) updatePayload.whatsapp_notified = data.whatsapp_notified;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.customer !== undefined) {
            await repair_orders.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.device !== undefined) {
            await repair_orders.setDevice(
              
              data.device,
              
              { transaction }
            );
        }
        

        
        

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

        return repair_orders;
    }

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

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

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


        return repair_orders;
    }

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

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

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

        await repair_orders.destroy({
            transaction
        });

        return repair_orders;
    }

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

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

        if (!repair_orders) {
            return repair_orders;
        }

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

        
        
        
        
        
        
        
        
        output.order_items_repair_order = await repair_orders.getOrder_items_repair_order({
            transaction
        });
        
        
        
        output.payments_repair_order = await repair_orders.getPayments_repair_order({
            transaction
        });
        
        
        output.invoices_repair_order = await repair_orders.getInvoices_repair_order({
            transaction
        });
        
        
        
        output.whatsapp_notifications_repair_order = await repair_orders.getWhatsapp_notifications_repair_order({
            transaction
        });
        
        
        
        
        
        
        output.customer = await repair_orders.getCustomer({
            transaction
        });
        
        
        output.device = await repair_orders.getDevice({
            transaction
        });
        
        
        output.intake_photos = await repair_orders.getIntake_photos({
            transaction
        });
        
        
        output.attachments = await repair_orders.getAttachments({
            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.customers,
        as: 'customer',
        
        where: filter.customer ? {
          [Op.or]: [
            { id: { [Op.in]: filter.customer.split('|').map(term => Utils.uuid(term)) } },
            {
              customer_code: {
                [Op.or]: filter.customer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

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

    ];

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

            
            if (filter.order_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'repair_orders',
                        'order_number',
                        filter.order_number,
                    ),
                };
            }
            
            if (filter.problem_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'repair_orders',
                        'problem_description',
                        filter.problem_description,
                    ),
                };
            }
            
            if (filter.diagnosis_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'repair_orders',
                        'diagnosis_notes',
                        filter.diagnosis_notes,
                    ),
                };
            }
            
            if (filter.internal_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'repair_orders',
                        'internal_notes',
                        filter.internal_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    estimated_ready_at: {
                    ...where.estimated_ready_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.delivered_atRange) {
                const [start, end] = filter.delivered_atRange;

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

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

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

            
            if (filter.source) {
                where = {
                    ...where,
                source: filter.source,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.requires_deposit) {
                where = {
                    ...where,
                requires_deposit: filter.requires_deposit,
            };
            }
            
            if (filter.whatsapp_notified) {
                where = {
                    ...where,
                whatsapp_notified: filter.whatsapp_notified,
            };
            }
            


      

      



            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.repair_orders.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(
                        'repair_orders',
                        'order_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

