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

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

        const certificates = await db.certificates.create(
            {
                id: data.id || undefined,
        
        subject_label: data.subject_label
        ||
        null
            ,
            
        level_label: data.level_label
        ||
        null
            ,
            
        issued_at: data.issued_at
        ||
        null
            ,
            
        certificate_html: data.certificate_html
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await certificates.setBooking( data.booking || null, {
            transaction,
        });
        
        await certificates.setLearner( data.learner || null, {
            transaction,
        });
        
        await certificates.setTutor( data.tutor || null, {
            transaction,
        });
        

        

        

        return certificates;
    }
    

    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 certificatesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                subject_label: item.subject_label
            ||
            null
            ,
            
                level_label: item.level_label
            ||
            null
            ,
            
                issued_at: item.issued_at
            ||
            null
            ,
            
                certificate_html: item.certificate_html
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return certificates;
    }

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

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


        

        const updatePayload = {};
        
        if (data.subject_label !== undefined) updatePayload.subject_label = data.subject_label;
        
        
        if (data.level_label !== undefined) updatePayload.level_label = data.level_label;
        
        
        if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
        
        
        if (data.certificate_html !== undefined) updatePayload.certificate_html = data.certificate_html;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.booking !== undefined) {
            await certificates.setBooking(
              
              data.booking,
              
              { transaction }
            );
        }
        
        if (data.learner !== undefined) {
            await certificates.setLearner(
              
              data.learner,
              
              { transaction }
            );
        }
        
        if (data.tutor !== undefined) {
            await certificates.setTutor(
              
              data.tutor,
              
              { transaction }
            );
        }
        

        
        

        

        return certificates;
    }

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

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

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


        return certificates;
    }

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

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

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

        await certificates.destroy({
            transaction
        });

        return certificates;
    }

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

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

        if (!certificates) {
            return certificates;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.booking = await certificates.getBooking({
            transaction
        });
        
        
        output.learner = await certificates.getLearner({
            transaction
        });
        
        
        output.tutor = await certificates.getTutor({
            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.bookings,
        as: 'booking',
        
        where: filter.booking ? {
          [Op.or]: [
            { id: { [Op.in]: filter.booking.split('|').map(term => Utils.uuid(term)) } },
            {
              level_name: {
                [Op.or]: filter.booking.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.subject_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'certificates',
                        'subject_label',
                        filter.subject_label,
                    ),
                };
            }
            
            if (filter.level_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'certificates',
                        'level_label',
                        filter.level_label,
                    ),
                };
            }
            
            if (filter.certificate_html) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'certificates',
                        'certificate_html',
                        filter.certificate_html,
                    ),
                };
            }
            

            
            

            
            if (filter.issued_atRange) {
                const [start, end] = filter.issued_atRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    issued_at: {
                    ...where.issued_at,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    issued_at: {
                    ...where.issued_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

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

            


      

      

      



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

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

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

    
};

