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

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

        const service_acceptance_notes = await db.service_acceptance_notes.create(
            {
                id: data.id || undefined,
        
        san_number: data.san_number
        ||
        null
            ,
            
        acceptance_date: data.acceptance_date
        ||
        null
            ,
            
        deliverable_checklist: data.deliverable_checklist
        ||
        null
            ,
            
        acceptance_criteria: data.acceptance_criteria
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await service_acceptance_notes.setTenant( data.tenant || null, {
            transaction,
        });
        
        await service_acceptance_notes.setPurchase_order( data.purchase_order || null, {
            transaction,
        });
        
        await service_acceptance_notes.setAccepted_by( data.accepted_by || null, {
            transaction,
        });
        
        await service_acceptance_notes.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return service_acceptance_notes;
    }
    

    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 service_acceptance_notesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                san_number: item.san_number
            ||
            null
            ,
            
                acceptance_date: item.acceptance_date
            ||
            null
            ,
            
                deliverable_checklist: item.deliverable_checklist
            ||
            null
            ,
            
                acceptance_criteria: item.acceptance_criteria
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return service_acceptance_notes;
    }

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

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


        

        const updatePayload = {};
        
        if (data.san_number !== undefined) updatePayload.san_number = data.san_number;
        
        
        if (data.acceptance_date !== undefined) updatePayload.acceptance_date = data.acceptance_date;
        
        
        if (data.deliverable_checklist !== undefined) updatePayload.deliverable_checklist = data.deliverable_checklist;
        
        
        if (data.acceptance_criteria !== undefined) updatePayload.acceptance_criteria = data.acceptance_criteria;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await service_acceptance_notes.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.purchase_order !== undefined) {
            await service_acceptance_notes.setPurchase_order(
              
              data.purchase_order,
              
              { transaction }
            );
        }
        
        if (data.accepted_by !== undefined) {
            await service_acceptance_notes.setAccepted_by(
              
              data.accepted_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await service_acceptance_notes.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return service_acceptance_notes;
    }

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

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

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


        return service_acceptance_notes;
    }

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

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

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

        await service_acceptance_notes.destroy({
            transaction
        });

        return service_acceptance_notes;
    }

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

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

        if (!service_acceptance_notes) {
            return service_acceptance_notes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await service_acceptance_notes.getTenant({
            transaction
        });
        
        
        output.purchase_order = await service_acceptance_notes.getPurchase_order({
            transaction
        });
        
        
        output.accepted_by = await service_acceptance_notes.getAccepted_by({
            transaction
        });
        
        
        output.evidence_files = await service_acceptance_notes.getEvidence_files({
            transaction
        });
        
        
        output.organizations = await service_acceptance_notes.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



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

    ];

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

            
            if (filter.san_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'service_acceptance_notes',
                        'san_number',
                        filter.san_number,
                    ),
                };
            }
            
            if (filter.deliverable_checklist) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'service_acceptance_notes',
                        'deliverable_checklist',
                        filter.deliverable_checklist,
                    ),
                };
            }
            
            if (filter.acceptance_criteria) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'service_acceptance_notes',
                        'acceptance_criteria',
                        filter.acceptance_criteria,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    acceptance_date: {
                    ...where.acceptance_date,
                            [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.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.service_acceptance_notes.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'service_acceptance_notes',
                        'san_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

