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

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

        const insurance_policies = await db.insurance_policies.create(
            {
                id: data.id || undefined,
        
        provider_name: data.provider_name
        ||
        null
            ,
            
        policy_number: data.policy_number
        ||
        null
            ,
            
        group_number: data.group_number
        ||
        null
            ,
            
        coverage_type: data.coverage_type
        ||
        null
            ,
            
        contact_phone: data.contact_phone
        ||
        null
            ,
            
        claims_contact: data.claims_contact
        ||
        null
            ,
            
        preauthorisation_notes: data.preauthorisation_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

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

        return insurance_policies;
    }
    

    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 insurance_policiesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                provider_name: item.provider_name
            ||
            null
            ,
            
                policy_number: item.policy_number
            ||
            null
            ,
            
                group_number: item.group_number
            ||
            null
            ,
            
                coverage_type: item.coverage_type
            ||
            null
            ,
            
                contact_phone: item.contact_phone
            ||
            null
            ,
            
                claims_contact: item.claims_contact
            ||
            null
            ,
            
                preauthorisation_notes: item.preauthorisation_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return insurance_policies;
    }

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

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


        

        const updatePayload = {};
        
        if (data.provider_name !== undefined) updatePayload.provider_name = data.provider_name;
        
        
        if (data.policy_number !== undefined) updatePayload.policy_number = data.policy_number;
        
        
        if (data.group_number !== undefined) updatePayload.group_number = data.group_number;
        
        
        if (data.coverage_type !== undefined) updatePayload.coverage_type = data.coverage_type;
        
        
        if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
        
        
        if (data.claims_contact !== undefined) updatePayload.claims_contact = data.claims_contact;
        
        
        if (data.preauthorisation_notes !== undefined) updatePayload.preauthorisation_notes = data.preauthorisation_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return insurance_policies;
    }

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

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

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


        return insurance_policies;
    }

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

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

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

        await insurance_policies.destroy({
            transaction
        });

        return insurance_policies;
    }

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

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

        if (!insurance_policies) {
            return insurance_policies;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await insurance_policies.getUser({
            transaction
        });
        
        
        output.eob_files = await insurance_policies.getEob_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.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}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.provider_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'insurance_policies',
                        'provider_name',
                        filter.provider_name,
                    ),
                };
            }
            
            if (filter.policy_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'insurance_policies',
                        'policy_number',
                        filter.policy_number,
                    ),
                };
            }
            
            if (filter.group_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'insurance_policies',
                        'group_number',
                        filter.group_number,
                    ),
                };
            }
            
            if (filter.coverage_type) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'insurance_policies',
                        'coverage_type',
                        filter.coverage_type,
                    ),
                };
            }
            
            if (filter.contact_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'insurance_policies',
                        'contact_phone',
                        filter.contact_phone,
                    ),
                };
            }
            
            if (filter.claims_contact) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'insurance_policies',
                        'claims_contact',
                        filter.claims_contact,
                    ),
                };
            }
            
            if (filter.preauthorisation_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'insurance_policies',
                        'preauthorisation_notes',
                        filter.preauthorisation_notes,
                    ),
                };
            }
            

            
            

            

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

            


      



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

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

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

    
};

