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

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

        const certificates_of_analysis = await db.certificates_of_analysis.create(
            {
                id: data.id || undefined,
        
        coa_number: data.coa_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        issued_at: data.issued_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await certificates_of_analysis.setBatch( data.batch || null, {
            transaction,
        });
        
        await certificates_of_analysis.setSupplier( data.supplier || null, {
            transaction,
        });
        
        await certificates_of_analysis.setIssued_by( data.issued_by || null, {
            transaction,
        });
        

        

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

        return certificates_of_analysis;
    }
    

    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 certificates_of_analysisData = data.map((item, index) => ({
                id: item.id || undefined,
                
                coa_number: item.coa_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                issued_at: item.issued_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return certificates_of_analysis;
    }

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

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


        

        const updatePayload = {};
        
        if (data.coa_number !== undefined) updatePayload.coa_number = data.coa_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.batch !== undefined) {
            await certificates_of_analysis.setBatch(
              
              data.batch,
              
              { transaction }
            );
        }
        
        if (data.supplier !== undefined) {
            await certificates_of_analysis.setSupplier(
              
              data.supplier,
              
              { transaction }
            );
        }
        
        if (data.issued_by !== undefined) {
            await certificates_of_analysis.setIssued_by(
              
              data.issued_by,
              
              { transaction }
            );
        }
        

        
        

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

        return certificates_of_analysis;
    }

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

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

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


        return certificates_of_analysis;
    }

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

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

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

        await certificates_of_analysis.destroy({
            transaction
        });

        return certificates_of_analysis;
    }

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

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

        if (!certificates_of_analysis) {
            return certificates_of_analysis;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.batch = await certificates_of_analysis.getBatch({
            transaction
        });
        
        
        output.supplier = await certificates_of_analysis.getSupplier({
            transaction
        });
        
        
        output.coa_files = await certificates_of_analysis.getCoa_files({
            transaction
        });
        
        
        output.issued_by = await certificates_of_analysis.getIssued_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.batches,
        as: 'batch',
        
        where: filter.batch ? {
          [Op.or]: [
            { id: { [Op.in]: filter.batch.split('|').map(term => Utils.uuid(term)) } },
            {
              batch_number: {
                [Op.or]: filter.batch.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

            
            if (filter.coa_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'certificates_of_analysis',
                        'coa_number',
                        filter.coa_number,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'certificates_of_analysis',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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


      

      

      



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

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

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

    
};

