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

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

        const suppliers = await db.suppliers.create(
            {
                id: data.id || undefined,
        
        supplier_name: data.supplier_name
        ||
        null
            ,
            
        supplier_code: data.supplier_code
        ||
        null
            ,
            
        supplier_type: data.supplier_type
        ||
        null
            ,
            
        contact_name: data.contact_name
        ||
        null
            ,
            
        contact_email: data.contact_email
        ||
        null
            ,
            
        contact_phone: data.contact_phone
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        qualification_status: data.qualification_status
        ||
        null
            ,
            
        last_audit_at: data.last_audit_at
        ||
        null
            ,
            
        next_audit_at: data.next_audit_at
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return suppliers;
    }
    

    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 suppliersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                supplier_name: item.supplier_name
            ||
            null
            ,
            
                supplier_code: item.supplier_code
            ||
            null
            ,
            
                supplier_type: item.supplier_type
            ||
            null
            ,
            
                contact_name: item.contact_name
            ||
            null
            ,
            
                contact_email: item.contact_email
            ||
            null
            ,
            
                contact_phone: item.contact_phone
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                qualification_status: item.qualification_status
            ||
            null
            ,
            
                last_audit_at: item.last_audit_at
            ||
            null
            ,
            
                next_audit_at: item.next_audit_at
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return suppliers;
    }

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

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


        

        const updatePayload = {};
        
        if (data.supplier_name !== undefined) updatePayload.supplier_name = data.supplier_name;
        
        
        if (data.supplier_code !== undefined) updatePayload.supplier_code = data.supplier_code;
        
        
        if (data.supplier_type !== undefined) updatePayload.supplier_type = data.supplier_type;
        
        
        if (data.contact_name !== undefined) updatePayload.contact_name = data.contact_name;
        
        
        if (data.contact_email !== undefined) updatePayload.contact_email = data.contact_email;
        
        
        if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.qualification_status !== undefined) updatePayload.qualification_status = data.qualification_status;
        
        
        if (data.last_audit_at !== undefined) updatePayload.last_audit_at = data.last_audit_at;
        
        
        if (data.next_audit_at !== undefined) updatePayload.next_audit_at = data.next_audit_at;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return suppliers;
    }

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

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

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


        return suppliers;
    }

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

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

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

        await suppliers.destroy({
            transaction
        });

        return suppliers;
    }

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

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

        if (!suppliers) {
            return suppliers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.certificates_of_analysis_supplier = await suppliers.getCertificates_of_analysis_supplier({
            transaction
        });
        
        
        
        
        
        
        output.nonconformances_supplier = await suppliers.getNonconformances_supplier({
            transaction
        });
        
        
        
        output.audits_supplier = await suppliers.getAudits_supplier({
            transaction
        });
        
        
        
        
        
        
        
        output.supplier_files = await suppliers.getSupplier_files({
            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.file,
        as: 'supplier_files',
      },

    ];

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

            
            if (filter.supplier_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'supplier_name',
                        filter.supplier_name,
                    ),
                };
            }
            
            if (filter.supplier_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'supplier_code',
                        filter.supplier_code,
                    ),
                };
            }
            
            if (filter.contact_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'contact_name',
                        filter.contact_name,
                    ),
                };
            }
            
            if (filter.contact_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'contact_email',
                        filter.contact_email,
                    ),
                };
            }
            
            if (filter.contact_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'contact_phone',
                        filter.contact_phone,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'suppliers',
                        'address',
                        filter.address,
                    ),
                };
            }
            

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

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

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

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

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

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

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

            
            if (filter.supplier_type) {
                where = {
                    ...where,
                supplier_type: filter.supplier_type,
            };
            }
            
            if (filter.qualification_status) {
                where = {
                    ...where,
                qualification_status: filter.qualification_status,
            };
            }
            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.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.suppliers.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(
                        'suppliers',
                        'supplier_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

