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

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

        const student_parent_links = await db.student_parent_links.create(
            {
                id: data.id || undefined,
        
        relationship_type: data.relationship_type
        ||
        null
            ,
            
        primary_contact: data.primary_contact
        ||
        false
        
            ,
            
        pickup_authorized: data.pickup_authorized
        ||
        false
        
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await student_parent_links.setStudent( data.student || null, {
            transaction,
        });
        
        await student_parent_links.setParent( data.parent || null, {
            transaction,
        });
        

        

        

        return student_parent_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 student_parent_linksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                relationship_type: item.relationship_type
            ||
            null
            ,
            
                primary_contact: item.primary_contact
            ||
            false
        
            ,
            
                pickup_authorized: item.pickup_authorized
            ||
            false
        
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return student_parent_links;
    }

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

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


        

        const updatePayload = {};
        
        if (data.relationship_type !== undefined) updatePayload.relationship_type = data.relationship_type;
        
        
        if (data.primary_contact !== undefined) updatePayload.primary_contact = data.primary_contact;
        
        
        if (data.pickup_authorized !== undefined) updatePayload.pickup_authorized = data.pickup_authorized;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.student !== undefined) {
            await student_parent_links.setStudent(
              
              data.student,
              
              { transaction }
            );
        }
        
        if (data.parent !== undefined) {
            await student_parent_links.setParent(
              
              data.parent,
              
              { transaction }
            );
        }
        

        
        

        

        return student_parent_links;
    }

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

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

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


        return student_parent_links;
    }

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

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

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

        await student_parent_links.destroy({
            transaction
        });

        return student_parent_links;
    }

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

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

        if (!student_parent_links) {
            return student_parent_links;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.student = await student_parent_links.getStudent({
            transaction
        });
        
        
        output.parent = await student_parent_links.getParent({
            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.students,
        as: 'student',
        
        where: filter.student ? {
          [Op.or]: [
            { id: { [Op.in]: filter.student.split('|').map(term => Utils.uuid(term)) } },
            {
              student_number: {
                [Op.or]: filter.student.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.parents,
        as: 'parent',
        
        where: filter.parent ? {
          [Op.or]: [
            { id: { [Op.in]: filter.parent.split('|').map(term => Utils.uuid(term)) } },
            {
              relationship_type: {
                [Op.or]: filter.parent.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.relationship_type) {
                where = {
                    ...where,
                relationship_type: filter.relationship_type,
            };
            }
            
            if (filter.primary_contact) {
                where = {
                    ...where,
                primary_contact: filter.primary_contact,
            };
            }
            
            if (filter.pickup_authorized) {
                where = {
                    ...where,
                pickup_authorized: filter.pickup_authorized,
            };
            }
            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.active,
            };
            }
            


      

      



            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.student_parent_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, ) {
        let where = {};
        
        

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

        const records = await db.student_parent_links.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,
        }));
    }

    
};

