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

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

        const company_insurances = await db.company_insurances.create(
            {
                id: data.id || undefined,
        
        type: data.type
        ||
        null
            ,
            
        provider: data.provider
        ||
        null
            ,
            
        policy_number: data.policy_number
        ||
        null
            ,
            
        broker: data.broker
        ||
        null
            ,
            
        coverage_amount: data.coverage_amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        valid_from: data.valid_from
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        contact_name: data.contact_name
        ||
        null
            ,
            
        contact_email: data.contact_email
        ||
        null
            ,
            
        contact_phone: data.contact_phone
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await company_insurances.setCompany( data.company || null, {
            transaction,
        });
        

        

        

        return company_insurances;
    }
    

    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 company_insurancesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                type: item.type
            ||
            null
            ,
            
                provider: item.provider
            ||
            null
            ,
            
                policy_number: item.policy_number
            ||
            null
            ,
            
                broker: item.broker
            ||
            null
            ,
            
                coverage_amount: item.coverage_amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                valid_from: item.valid_from
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                contact_name: item.contact_name
            ||
            null
            ,
            
                contact_email: item.contact_email
            ||
            null
            ,
            
                contact_phone: item.contact_phone
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return company_insurances;
    }

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

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


        

        const updatePayload = {};
        
        if (data.type !== undefined) updatePayload.type = data.type;
        
        
        if (data.provider !== undefined) updatePayload.provider = data.provider;
        
        
        if (data.policy_number !== undefined) updatePayload.policy_number = data.policy_number;
        
        
        if (data.broker !== undefined) updatePayload.broker = data.broker;
        
        
        if (data.coverage_amount !== undefined) updatePayload.coverage_amount = data.coverage_amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.valid_from !== undefined) updatePayload.valid_from = data.valid_from;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.contact_name !== undefined) updatePayload.contact_name = data.contact_name;
        
        
        if (data.contact_email !== undefined) updatePayload.contact_email = data.contact_email;
        
        
        if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await company_insurances.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        

        
        

        

        return company_insurances;
    }

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

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

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


        return company_insurances;
    }

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

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

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

        await company_insurances.destroy({
            transaction
        });

        return company_insurances;
    }

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

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

        if (!company_insurances) {
            return company_insurances;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await company_insurances.getCompany({
            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.companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.provider) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_insurances',
                        'provider',
                        filter.provider,
                    ),
                };
            }
            
            if (filter.policy_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_insurances',
                        'policy_number',
                        filter.policy_number,
                    ),
                };
            }
            
            if (filter.broker) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_insurances',
                        'broker',
                        filter.broker,
                    ),
                };
            }
            
            if (filter.contact_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_insurances',
                        'contact_name',
                        filter.contact_name,
                    ),
                };
            }
            
            if (filter.contact_email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_insurances',
                        'contact_email',
                        filter.contact_email,
                    ),
                };
            }
            
            if (filter.contact_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_insurances',
                        'contact_phone',
                        filter.contact_phone,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'company_insurances',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    valid_from: {
                    ...where.valid_from,
                            [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.type) {
                where = {
                    ...where,
                type: filter.type,
            };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                currency: filter.currency,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      



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

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

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

    
};

