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

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

        const parents = await db.parents.create(
            {
                id: data.id || undefined,
        
        relationship_type: data.relationship_type
        ||
        null
            ,
            
        occupation: data.occupation
        ||
        null
            ,
            
        can_view_grades: data.can_view_grades
        ||
        false
        
            ,
            
        can_view_attendance: data.can_view_attendance
        ||
        false
        
            ,
            
        can_message_staff: data.can_message_staff
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await parents.setUser( data.user || null, {
            transaction,
        });
        
        await parents.setSchool( data.school || null, {
            transaction,
        });
        

        

        

        return parents;
    }
    

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

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

        // For each item created, replace relation files
        

        return parents;
    }

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

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


        

        const updatePayload = {};
        
        if (data.relationship_type !== undefined) updatePayload.relationship_type = data.relationship_type;
        
        
        if (data.occupation !== undefined) updatePayload.occupation = data.occupation;
        
        
        if (data.can_view_grades !== undefined) updatePayload.can_view_grades = data.can_view_grades;
        
        
        if (data.can_view_attendance !== undefined) updatePayload.can_view_attendance = data.can_view_attendance;
        
        
        if (data.can_message_staff !== undefined) updatePayload.can_message_staff = data.can_message_staff;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return parents;
    }

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

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

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


        return parents;
    }

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

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

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

        await parents.destroy({
            transaction
        });

        return parents;
    }

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

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

        if (!parents) {
            return parents;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.student_parent_links_parent = await parents.getStudent_parent_links_parent({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await parents.getUser({
            transaction
        });
        
        
        output.school = await parents.getSchool({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

            

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

            
            if (filter.relationship_type) {
                where = {
                    ...where,
                relationship_type: filter.relationship_type,
            };
            }
            
            if (filter.can_view_grades) {
                where = {
                    ...where,
                can_view_grades: filter.can_view_grades,
            };
            }
            
            if (filter.can_view_attendance) {
                where = {
                    ...where,
                can_view_attendance: filter.can_view_attendance,
            };
            }
            
            if (filter.can_message_staff) {
                where = {
                    ...where,
                can_message_staff: filter.can_message_staff,
            };
            }
            


      

      



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

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

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

    
};

