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

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

        const guardians = await db.guardians.create(
            {
                id: data.id || undefined,
        
        guardian_name: data.guardian_name
        ||
        null
            ,
            
        relationship: data.relationship
        ||
        null
            ,
            
        phone_number: data.phone_number
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await guardians.setSchool( data.school || null, {
            transaction,
        });
        

        

        

        return guardians;
    }
    

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

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

        // For each item created, replace relation files
        

        return guardians;
    }

    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 guardians = await db.guardians.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.guardian_name !== undefined) updatePayload.guardian_name = data.guardian_name;
        
        
        if (data.relationship !== undefined) updatePayload.relationship = data.relationship;
        
        
        if (data.phone_number !== undefined) updatePayload.phone_number = data.phone_number;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return guardians;
    }

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

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

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


        return guardians;
    }

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

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

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

        await guardians.destroy({
            transaction
        });

        return guardians;
    }

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

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

        if (!guardians) {
            return guardians;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.school = await guardians.getSchool({
            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.schools,
        as: 'school',
        
      },



    ];

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

            
            if (filter.guardian_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guardians',
                        'guardian_name',
                        filter.guardian_name,
                    ),
                };
            }
            
            if (filter.relationship) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guardians',
                        'relationship',
                        filter.relationship,
                    ),
                };
            }
            
            if (filter.phone_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guardians',
                        'phone_number',
                        filter.phone_number,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guardians',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guardians',
                        'address',
                        filter.address,
                    ),
                };
            }
            

            
            

            

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

            


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

        where = {
          ...where,
          schoolId: {[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.guardians.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(
                        'guardians',
                        'guardian_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

