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

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

        const guardians = await db.guardians.create(
            {
                id: data.id || undefined,
        
        primary_phone: data.primary_phone
        ||
        null
            ,
            
        secondary_phone: data.secondary_phone
        ||
        null
            ,
            
        address_line1: data.address_line1
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        state: data.state
        ||
        null
            ,
            
        postal_code: data.postal_code
        ||
        null
            ,
            
        emergency_contact_name: data.emergency_contact_name
        ||
        null
            ,
            
        emergency_contact_phone: data.emergency_contact_phone
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return guardians;
    }
    

    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 guardiansData = data.map((item, index) => ({
                id: item.id || undefined,
                
                primary_phone: item.primary_phone
            ||
            null
            ,
            
                secondary_phone: item.secondary_phone
            ||
            null
            ,
            
                address_line1: item.address_line1
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                state: item.state
            ||
            null
            ,
            
                postal_code: item.postal_code
            ||
            null
            ,
            
                emergency_contact_name: item.emergency_contact_name
            ||
            null
            ,
            
                emergency_contact_phone: item.emergency_contact_phone
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return guardians;
    }

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

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


        

        const updatePayload = {};
        
        if (data.primary_phone !== undefined) updatePayload.primary_phone = data.primary_phone;
        
        
        if (data.secondary_phone !== undefined) updatePayload.secondary_phone = data.secondary_phone;
        
        
        if (data.address_line1 !== undefined) updatePayload.address_line1 = data.address_line1;
        
        
        if (data.city !== undefined) updatePayload.city = data.city;
        
        
        if (data.state !== undefined) updatePayload.state = data.state;
        
        
        if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
        
        
        if (data.emergency_contact_name !== undefined) updatePayload.emergency_contact_name = data.emergency_contact_name;
        
        
        if (data.emergency_contact_phone !== undefined) updatePayload.emergency_contact_phone = data.emergency_contact_phone;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return guardians;
    }

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

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

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


        return guardians;
    }

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

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

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

        await guardians.destroy({
            transaction
        });

        return guardians;
    }

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

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

        if (!guardians) {
            return guardians;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.campers_primary_guardian = await guardians.getCampers_primary_guardian({
            transaction
        });
        
        
        
        
        
        output.document_signatures_guardian = await guardians.getDocument_signatures_guardian({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await guardians.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.primary_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guardians',
                        'primary_phone',
                        filter.primary_phone,
                    ),
                };
            }
            
            if (filter.secondary_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guardians',
                        'secondary_phone',
                        filter.secondary_phone,
                    ),
                };
            }
            
            if (filter.address_line1) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guardians',
                        'address_line1',
                        filter.address_line1,
                    ),
                };
            }
            
            if (filter.city) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guardians',
                        'city',
                        filter.city,
                    ),
                };
            }
            
            if (filter.state) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guardians',
                        'state',
                        filter.state,
                    ),
                };
            }
            
            if (filter.postal_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guardians',
                        'postal_code',
                        filter.postal_code,
                    ),
                };
            }
            
            if (filter.emergency_contact_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guardians',
                        'emergency_contact_name',
                        filter.emergency_contact_name,
                    ),
                };
            }
            
            if (filter.emergency_contact_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guardians',
                        'emergency_contact_phone',
                        filter.emergency_contact_phone,
                    ),
                };
            }
            

            
            

            

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

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

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

    
};

