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

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

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

        
        await parent_student_links.setParent_user( data.parent_user || null, {
            transaction,
        });
        
        await parent_student_links.setStudent( data.student || null, {
            transaction,
        });
        
        await parent_student_links.setSchools( data.schools || null, {
            transaction,
        });
        

        

        

        return parent_student_links;
    }
    

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

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

        // For each item created, replace relation files
        

        return parent_student_links;
    }

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

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


        

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

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

        
        
        if (data.parent_user !== undefined) {
            await parent_student_links.setParent_user(
              
              data.parent_user,
              
              { transaction }
            );
        }
        
        if (data.student !== undefined) {
            await parent_student_links.setStudent(
              
              data.student,
              
              { transaction }
            );
        }
        
        if (data.schools !== undefined) {
            await parent_student_links.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        

        

        return parent_student_links;
    }

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

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

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


        return parent_student_links;
    }

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

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

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

        await parent_student_links.destroy({
            transaction
        });

        return parent_student_links;
    }

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

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

        if (!parent_student_links) {
            return parent_student_links;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.parent_user = await parent_student_links.getParent_user({
            transaction
        });
        
        
        output.student = await parent_student_links.getStudent({
            transaction
        });
        
        
        output.schools = await parent_student_links.getSchools({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userSchools = (user && user.schools?.id) || null;
        

        
        if (userSchools) {
            if (options?.currentUser?.schoolsId) {
                where.schoolsId = options.currentUser.schoolsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

      {
        model: db.schools,
        as: 'schools',
        
      },



    ];

        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.relationship) {
                where = {
                    ...where,
                relationship: filter.relationship,
            };
            }
            
            if (filter.is_primary) {
                where = {
                    ...where,
                is_primary: filter.is_primary,
            };
            }
            


      

      

      
      if (filter.schools) {
        const listItems = filter.schools.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          schoolsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.schoolsId;
        }
        

        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.parent_student_links.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'parent_student_links',
                        'relationship',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

