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

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

        const emergency_medical_cards = await db.emergency_medical_cards.create(
            {
                id: data.id || undefined,
        
        full_name: data.full_name
        ||
        null
            ,
            
        date_of_birth: data.date_of_birth
        ||
        null
            ,
            
        blood_type: data.blood_type
        ||
        null
            ,
            
        critical_allergies: data.critical_allergies
        ||
        null
            ,
            
        critical_conditions: data.critical_conditions
        ||
        null
            ,
            
        critical_medications: data.critical_medications
        ||
        null
            ,
            
        emergency_contacts: data.emergency_contacts
        ||
        null
            ,
            
        treating_doctor_contact: data.treating_doctor_contact
        ||
        null
            ,
            
        organ_donor_status: data.organ_donor_status
        ||
        null
            ,
            
        advance_directives_summary: data.advance_directives_summary
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await emergency_medical_cards.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return emergency_medical_cards;
    }
    

    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 emergency_medical_cardsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                full_name: item.full_name
            ||
            null
            ,
            
                date_of_birth: item.date_of_birth
            ||
            null
            ,
            
                blood_type: item.blood_type
            ||
            null
            ,
            
                critical_allergies: item.critical_allergies
            ||
            null
            ,
            
                critical_conditions: item.critical_conditions
            ||
            null
            ,
            
                critical_medications: item.critical_medications
            ||
            null
            ,
            
                emergency_contacts: item.emergency_contacts
            ||
            null
            ,
            
                treating_doctor_contact: item.treating_doctor_contact
            ||
            null
            ,
            
                organ_donor_status: item.organ_donor_status
            ||
            null
            ,
            
                advance_directives_summary: item.advance_directives_summary
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return emergency_medical_cards;
    }

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

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


        

        const updatePayload = {};
        
        if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
        
        
        if (data.date_of_birth !== undefined) updatePayload.date_of_birth = data.date_of_birth;
        
        
        if (data.blood_type !== undefined) updatePayload.blood_type = data.blood_type;
        
        
        if (data.critical_allergies !== undefined) updatePayload.critical_allergies = data.critical_allergies;
        
        
        if (data.critical_conditions !== undefined) updatePayload.critical_conditions = data.critical_conditions;
        
        
        if (data.critical_medications !== undefined) updatePayload.critical_medications = data.critical_medications;
        
        
        if (data.emergency_contacts !== undefined) updatePayload.emergency_contacts = data.emergency_contacts;
        
        
        if (data.treating_doctor_contact !== undefined) updatePayload.treating_doctor_contact = data.treating_doctor_contact;
        
        
        if (data.organ_donor_status !== undefined) updatePayload.organ_donor_status = data.organ_donor_status;
        
        
        if (data.advance_directives_summary !== undefined) updatePayload.advance_directives_summary = data.advance_directives_summary;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await emergency_medical_cards.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return emergency_medical_cards;
    }

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

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

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


        return emergency_medical_cards;
    }

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

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

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

        await emergency_medical_cards.destroy({
            transaction
        });

        return emergency_medical_cards;
    }

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

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

        if (!emergency_medical_cards) {
            return emergency_medical_cards;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await emergency_medical_cards.getUser({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.full_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'emergency_medical_cards',
                        'full_name',
                        filter.full_name,
                    ),
                };
            }
            
            if (filter.blood_type) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'emergency_medical_cards',
                        'blood_type',
                        filter.blood_type,
                    ),
                };
            }
            
            if (filter.critical_allergies) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'emergency_medical_cards',
                        'critical_allergies',
                        filter.critical_allergies,
                    ),
                };
            }
            
            if (filter.critical_conditions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'emergency_medical_cards',
                        'critical_conditions',
                        filter.critical_conditions,
                    ),
                };
            }
            
            if (filter.critical_medications) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'emergency_medical_cards',
                        'critical_medications',
                        filter.critical_medications,
                    ),
                };
            }
            
            if (filter.emergency_contacts) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'emergency_medical_cards',
                        'emergency_contacts',
                        filter.emergency_contacts,
                    ),
                };
            }
            
            if (filter.treating_doctor_contact) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'emergency_medical_cards',
                        'treating_doctor_contact',
                        filter.treating_doctor_contact,
                    ),
                };
            }
            
            if (filter.advance_directives_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'emergency_medical_cards',
                        'advance_directives_summary',
                        filter.advance_directives_summary,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.organ_donor_status) {
                where = {
                    ...where,
                organ_donor_status: filter.organ_donor_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.emergency_medical_cards.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(
                        'emergency_medical_cards',
                        'full_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

