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

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

        const alumni = await db.alumni.create(
            {
                id: data.id || undefined,
        
        full_name: data.full_name
        ||
        null
            ,
            
        graduation_year: data.graduation_year
        ||
        null
            ,
            
        current_role: data.current_role
        ||
        null
            ,
            
        organization: data.organization
        ||
        null
            ,
            
        bio: data.bio
        ||
        null
            ,
            
        phone_number: data.phone_number
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        notable: data.notable
        ||
        false
        
            ,
            
        published: data.published
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.alumni.getTableName(),
                belongsToColumn: 'photo',
                belongsToId: alumni.id,
            },
            data.photo,
            options,
        );
        

        return alumni;
    }
    

    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 alumniData = data.map((item, index) => ({
                id: item.id || undefined,
                
                full_name: item.full_name
            ||
            null
            ,
            
                graduation_year: item.graduation_year
            ||
            null
            ,
            
                current_role: item.current_role
            ||
            null
            ,
            
                organization: item.organization
            ||
            null
            ,
            
                bio: item.bio
            ||
            null
            ,
            
                phone_number: item.phone_number
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                notable: item.notable
            ||
            false
        
            ,
            
                published: item.published
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < alumni.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.alumni.getTableName(),
                    belongsToColumn: 'photo',
                    belongsToId: alumni[i].id,
                },
                data[i].photo,
                options,
            );
        }
        

        return alumni;
    }

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

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


        

        const updatePayload = {};
        
        if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
        
        
        if (data.graduation_year !== undefined) updatePayload.graduation_year = data.graduation_year;
        
        
        if (data.current_role !== undefined) updatePayload.current_role = data.current_role;
        
        
        if (data.organization !== undefined) updatePayload.organization = data.organization;
        
        
        if (data.bio !== undefined) updatePayload.bio = data.bio;
        
        
        if (data.phone_number !== undefined) updatePayload.phone_number = data.phone_number;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.notable !== undefined) updatePayload.notable = data.notable;
        
        
        if (data.published !== undefined) updatePayload.published = data.published;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.alumni.getTableName(),
                belongsToColumn: 'photo',
                belongsToId: alumni.id,
            },
            data.photo,
            options,
        );
        

        return alumni;
    }

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

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

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


        return alumni;
    }

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

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

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

        await alumni.destroy({
            transaction
        });

        return alumni;
    }

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

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

        if (!alumni) {
            return alumni;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.photo = await alumni.getPhoto({
            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.file,
        as: 'photo',
      },

    ];

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

            
            if (filter.full_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alumni',
                        'full_name',
                        filter.full_name,
                    ),
                };
            }
            
            if (filter.graduation_year) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alumni',
                        'graduation_year',
                        filter.graduation_year,
                    ),
                };
            }
            
            if (filter.current_role) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alumni',
                        'current_role',
                        filter.current_role,
                    ),
                };
            }
            
            if (filter.organization) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alumni',
                        'organization',
                        filter.organization,
                    ),
                };
            }
            
            if (filter.bio) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alumni',
                        'bio',
                        filter.bio,
                    ),
                };
            }
            
            if (filter.phone_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alumni',
                        'phone_number',
                        filter.phone_number,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'alumni',
                        'email',
                        filter.email,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.notable) {
                where = {
                    ...where,
                notable: filter.notable,
            };
            }
            
            if (filter.published) {
                where = {
                    ...where,
                published: filter.published,
            };
            }
            




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

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

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

    
};

