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

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

        const maternity_cases = await db.maternity_cases.create(
            {
                id: data.id || undefined,
        
        case_number: data.case_number
        ||
        null
            ,
            
        diagnosis: data.diagnosis
        ||
        null
            ,
            
        delivery_type: data.delivery_type
        ||
        null
            ,
            
        admission_date: data.admission_date
        ||
        null
            ,
            
        discharge_date: data.discharge_date
        ||
        null
            ,
            
        price: data.price
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await maternity_cases.setPatient( data.patient || null, {
            transaction,
        });
        
        await maternity_cases.setDoctor( data.doctor || null, {
            transaction,
        });
        

        

        

        return maternity_cases;
    }
    

    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 maternity_casesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                case_number: item.case_number
            ||
            null
            ,
            
                diagnosis: item.diagnosis
            ||
            null
            ,
            
                delivery_type: item.delivery_type
            ||
            null
            ,
            
                admission_date: item.admission_date
            ||
            null
            ,
            
                discharge_date: item.discharge_date
            ||
            null
            ,
            
                price: item.price
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return maternity_cases;
    }

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

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


        

        const updatePayload = {};
        
        if (data.case_number !== undefined) updatePayload.case_number = data.case_number;
        
        
        if (data.diagnosis !== undefined) updatePayload.diagnosis = data.diagnosis;
        
        
        if (data.delivery_type !== undefined) updatePayload.delivery_type = data.delivery_type;
        
        
        if (data.admission_date !== undefined) updatePayload.admission_date = data.admission_date;
        
        
        if (data.discharge_date !== undefined) updatePayload.discharge_date = data.discharge_date;
        
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await maternity_cases.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.doctor !== undefined) {
            await maternity_cases.setDoctor(
              
              data.doctor,
              
              { transaction }
            );
        }
        

        
        

        

        return maternity_cases;
    }

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

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

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


        return maternity_cases;
    }

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

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

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

        await maternity_cases.destroy({
            transaction
        });

        return maternity_cases;
    }

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

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

        if (!maternity_cases) {
            return maternity_cases;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await maternity_cases.getPatient({
            transaction
        });
        
        
        output.doctor = await maternity_cases.getDoctor({
            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.patients,
        as: 'patient',
        
        where: filter.patient ? {
          [Op.or]: [
            { id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.case_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'maternity_cases',
                        'case_number',
                        filter.case_number,
                    ),
                };
            }
            
            if (filter.diagnosis) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'maternity_cases',
                        'diagnosis',
                        filter.diagnosis,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


      

      



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

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

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

    
};

