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

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

        const family_memberships = await db.family_memberships.create(
            {
                id: data.id || undefined,
        
        role_in_family: data.role_in_family
        ||
        null
            ,
            
        is_head_of_household: data.is_head_of_household
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await family_memberships.setFamily( data.family || null, {
            transaction,
        });
        
        await family_memberships.setNpc( data.npc || null, {
            transaction,
        });
        

        

        

        return family_memberships;
    }
    

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

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

        // For each item created, replace relation files
        

        return family_memberships;
    }

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

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


        

        const updatePayload = {};
        
        if (data.role_in_family !== undefined) updatePayload.role_in_family = data.role_in_family;
        
        
        if (data.is_head_of_household !== undefined) updatePayload.is_head_of_household = data.is_head_of_household;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.family !== undefined) {
            await family_memberships.setFamily(
              
              data.family,
              
              { transaction }
            );
        }
        
        if (data.npc !== undefined) {
            await family_memberships.setNpc(
              
              data.npc,
              
              { transaction }
            );
        }
        

        
        

        

        return family_memberships;
    }

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

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

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


        return family_memberships;
    }

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

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

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

        await family_memberships.destroy({
            transaction
        });

        return family_memberships;
    }

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

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

        if (!family_memberships) {
            return family_memberships;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.family = await family_memberships.getFamily({
            transaction
        });
        
        
        output.npc = await family_memberships.getNpc({
            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.families,
        as: 'family',
        
        where: filter.family ? {
          [Op.or]: [
            { id: { [Op.in]: filter.family.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.family.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            

            

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

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


      

      



            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_memberships.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_memberships',
                        'role_in_family',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

