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

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

        const repair_services = await db.repair_services.create(
            {
                id: data.id || undefined,
        
        service_name: data.service_name
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        base_price: data.base_price
        ||
        null
            ,
            
        estimated_minutes: data.estimated_minutes
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return repair_services;
    }
    

    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_servicesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                service_name: item.service_name
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                base_price: item.base_price
            ||
            null
            ,
            
                estimated_minutes: item.estimated_minutes
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return repair_services;
    }

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

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


        

        const updatePayload = {};
        
        if (data.service_name !== undefined) updatePayload.service_name = data.service_name;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.base_price !== undefined) updatePayload.base_price = data.base_price;
        
        
        if (data.estimated_minutes !== undefined) updatePayload.estimated_minutes = data.estimated_minutes;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return repair_services;
    }

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

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

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


        return repair_services;
    }

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

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

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

        await repair_services.destroy({
            transaction
        });

        return repair_services;
    }

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

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

        if (!repair_services) {
            return repair_services;
        }

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

        
        
        
        
        
        
        
        
        output.order_items_repair_service = await repair_services.getOrder_items_repair_service({
            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 = [



    ];

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

            
            if (filter.service_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'repair_services',
                        'service_name',
                        filter.service_name,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'repair_services',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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




            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_services.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_services',
                        'service_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

