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

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

        const family_members = await db.family_members.create(
            {
                id: data.id || undefined,
        
        member_role: data.member_role
        ||
        null
            ,
            
        has_own_account: data.has_own_account
        ||
        false
        
            ,
            
        display_name: data.display_name
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await family_members.setFamily_group( data.family_group || null, {
            transaction,
        });
        
        await family_members.setUser( data.user || null, {
            transaction,
        });
        

        

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

        return family_members;
    }
    

    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 family_membersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                member_role: item.member_role
            ||
            null
            ,
            
                has_own_account: item.has_own_account
            ||
            false
        
            ,
            
                display_name: item.display_name
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return family_members;
    }

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

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


        

        const updatePayload = {};
        
        if (data.member_role !== undefined) updatePayload.member_role = data.member_role;
        
        
        if (data.has_own_account !== undefined) updatePayload.has_own_account = data.has_own_account;
        
        
        if (data.display_name !== undefined) updatePayload.display_name = data.display_name;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return family_members;
    }

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

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

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


        return family_members;
    }

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

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

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

        await family_members.destroy({
            transaction
        });

        return family_members;
    }

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

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

        if (!family_members) {
            return family_members;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.family_group = await family_members.getFamily_group({
            transaction
        });
        
        
        output.user = await family_members.getUser({
            transaction
        });
        
        
        output.avatar = await family_members.getAvatar({
            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.family_groups,
        as: 'family_group',
        
        where: filter.family_group ? {
          [Op.or]: [
            { id: { [Op.in]: filter.family_group.split('|').map(term => Utils.uuid(term)) } },
            {
              group_name: {
                [Op.or]: filter.family_group.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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: 'avatar',
      },

    ];

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

            
            if (filter.display_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'family_members',
                        'display_name',
                        filter.display_name,
                    ),
                };
            }
            

            
            

            

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

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


      

      



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

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

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

    
};

