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

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

        const tutor_profiles = await db.tutor_profiles.create(
            {
                id: data.id || undefined,
        
        headline: data.headline
        ||
        null
            ,
            
        teaching_type: data.teaching_type
        ||
        null
            ,
            
        institution_name: data.institution_name
        ||
        null
            ,
            
        degree_qualification: data.degree_qualification
        ||
        null
            ,
            
        graduation_year: data.graduation_year
        ||
        null
            ,
            
        session_language: data.session_language
        ||
        null
            ,
            
        teaching_format: data.teaching_format
        ||
        null
            ,
            
        verification_status: data.verification_status
        ||
        null
            ,
            
        verification_note: data.verification_note
        ||
        null
            ,
            
        rating: data.rating
        ||
        null
            ,
            
        total_sessions: data.total_sessions
        ||
        null
            ,
            
        total_reviews: data.total_reviews
        ||
        null
            ,
            
        response_rate: data.response_rate
        ||
        null
            ,
            
        response_time_hours: data.response_time_hours
        ||
        null
            ,
            
        badge_level: data.badge_level
        ||
        null
            ,
            
        vacation_mode: data.vacation_mode
        ||
        false
        
            ,
            
        max_concurrent_bookings: data.max_concurrent_bookings
        ||
        null
            ,
            
        jitsi_meet_meeting_id: data.jitsi_meet_meeting_id
        ||
        null
            ,
            
        jitsi_meet_password: data.jitsi_meet_password
        ||
        null
            ,
            
        availability_json: data.availability_json
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await tutor_profiles.setUser( data.user || null, {
            transaction,
        });
        

        
        await tutor_profiles.setSubject_categories(data.subject_categories || [], {
            transaction,
        });
        
        await tutor_profiles.setSubjects(data.subjects || [], {
            transaction,
        });
        
        await tutor_profiles.setLanguages(data.languages || [], {
            transaction,
        });
        

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

        return tutor_profiles;
    }
    

    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 tutor_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                headline: item.headline
            ||
            null
            ,
            
                teaching_type: item.teaching_type
            ||
            null
            ,
            
                institution_name: item.institution_name
            ||
            null
            ,
            
                degree_qualification: item.degree_qualification
            ||
            null
            ,
            
                graduation_year: item.graduation_year
            ||
            null
            ,
            
                session_language: item.session_language
            ||
            null
            ,
            
                teaching_format: item.teaching_format
            ||
            null
            ,
            
                verification_status: item.verification_status
            ||
            null
            ,
            
                verification_note: item.verification_note
            ||
            null
            ,
            
                rating: item.rating
            ||
            null
            ,
            
                total_sessions: item.total_sessions
            ||
            null
            ,
            
                total_reviews: item.total_reviews
            ||
            null
            ,
            
                response_rate: item.response_rate
            ||
            null
            ,
            
                response_time_hours: item.response_time_hours
            ||
            null
            ,
            
                badge_level: item.badge_level
            ||
            null
            ,
            
                vacation_mode: item.vacation_mode
            ||
            false
        
            ,
            
                max_concurrent_bookings: item.max_concurrent_bookings
            ||
            null
            ,
            
                jitsi_meet_meeting_id: item.jitsi_meet_meeting_id
            ||
            null
            ,
            
                jitsi_meet_password: item.jitsi_meet_password
            ||
            null
            ,
            
                availability_json: item.availability_json
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return tutor_profiles;
    }

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

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


        

        const updatePayload = {};
        
        if (data.headline !== undefined) updatePayload.headline = data.headline;
        
        
        if (data.teaching_type !== undefined) updatePayload.teaching_type = data.teaching_type;
        
        
        if (data.institution_name !== undefined) updatePayload.institution_name = data.institution_name;
        
        
        if (data.degree_qualification !== undefined) updatePayload.degree_qualification = data.degree_qualification;
        
        
        if (data.graduation_year !== undefined) updatePayload.graduation_year = data.graduation_year;
        
        
        if (data.session_language !== undefined) updatePayload.session_language = data.session_language;
        
        
        if (data.teaching_format !== undefined) updatePayload.teaching_format = data.teaching_format;
        
        
        if (data.verification_status !== undefined) updatePayload.verification_status = data.verification_status;
        
        
        if (data.verification_note !== undefined) updatePayload.verification_note = data.verification_note;
        
        
        if (data.rating !== undefined) updatePayload.rating = data.rating;
        
        
        if (data.total_sessions !== undefined) updatePayload.total_sessions = data.total_sessions;
        
        
        if (data.total_reviews !== undefined) updatePayload.total_reviews = data.total_reviews;
        
        
        if (data.response_rate !== undefined) updatePayload.response_rate = data.response_rate;
        
        
        if (data.response_time_hours !== undefined) updatePayload.response_time_hours = data.response_time_hours;
        
        
        if (data.badge_level !== undefined) updatePayload.badge_level = data.badge_level;
        
        
        if (data.vacation_mode !== undefined) updatePayload.vacation_mode = data.vacation_mode;
        
        
        if (data.max_concurrent_bookings !== undefined) updatePayload.max_concurrent_bookings = data.max_concurrent_bookings;
        
        
        if (data.jitsi_meet_meeting_id !== undefined) updatePayload.jitsi_meet_meeting_id = data.jitsi_meet_meeting_id;
        
        
        if (data.jitsi_meet_password !== undefined) updatePayload.jitsi_meet_password = data.jitsi_meet_password;
        
        
        if (data.availability_json !== undefined) updatePayload.availability_json = data.availability_json;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        
        if (data.subject_categories !== undefined) {
            await tutor_profiles.setSubject_categories(data.subject_categories, { transaction });
        }
        
        if (data.subjects !== undefined) {
            await tutor_profiles.setSubjects(data.subjects, { transaction });
        }
        
        if (data.languages !== undefined) {
            await tutor_profiles.setLanguages(data.languages, { transaction });
        }
        

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

        return tutor_profiles;
    }

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

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

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


        return tutor_profiles;
    }

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

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

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

        await tutor_profiles.destroy({
            transaction
        });

        return tutor_profiles;
    }

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

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

        if (!tutor_profiles) {
            return tutor_profiles;
        }

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

        
        
        
        
        
        
        
        
        
        output.gigs_tutor_profile = await tutor_profiles.getGigs_tutor_profile({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await tutor_profiles.getUser({
            transaction
        });
        
        
        output.subject_categories = await tutor_profiles.getSubject_categories({
            transaction
        });
        
        
        output.subjects = await tutor_profiles.getSubjects({
            transaction
        });
        
        
        output.languages = await tutor_profiles.getLanguages({
            transaction
        });
        
        
        output.verification_docs = await tutor_profiles.getVerification_docs({
            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.subject_categories,
        as: 'subject_categories',
        required: false,
      },

      {
        model: db.subjects,
        as: 'subjects',
        required: false,
      },

      {
        model: db.languages,
        as: 'languages',
        required: false,
      },


      {
        model: db.file,
        as: 'verification_docs',
      },

    ];

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

            
            if (filter.headline) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tutor_profiles',
                        'headline',
                        filter.headline,
                    ),
                };
            }
            
            if (filter.institution_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tutor_profiles',
                        'institution_name',
                        filter.institution_name,
                    ),
                };
            }
            
            if (filter.degree_qualification) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tutor_profiles',
                        'degree_qualification',
                        filter.degree_qualification,
                    ),
                };
            }
            
            if (filter.verification_note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tutor_profiles',
                        'verification_note',
                        filter.verification_note,
                    ),
                };
            }
            
            if (filter.jitsi_meet_meeting_id) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tutor_profiles',
                        'jitsi_meet_meeting_id',
                        filter.jitsi_meet_meeting_id,
                    ),
                };
            }
            
            if (filter.jitsi_meet_password) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tutor_profiles',
                        'jitsi_meet_password',
                        filter.jitsi_meet_password,
                    ),
                };
            }
            
            if (filter.availability_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tutor_profiles',
                        'availability_json',
                        filter.availability_json,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    graduation_year: {
                    ...where.graduation_year,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.ratingRange) {
                const [start, end] = filter.ratingRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    rating: {
                    ...where.rating,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.total_sessionsRange) {
                const [start, end] = filter.total_sessionsRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    total_sessions: {
                    ...where.total_sessions,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.total_reviewsRange) {
                const [start, end] = filter.total_reviewsRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    total_reviews: {
                    ...where.total_reviews,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.response_rateRange) {
                const [start, end] = filter.response_rateRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    response_rate: {
                    ...where.response_rate,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.response_time_hoursRange) {
                const [start, end] = filter.response_time_hoursRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    response_time_hours: {
                    ...where.response_time_hours,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.max_concurrent_bookingsRange) {
                const [start, end] = filter.max_concurrent_bookingsRange;

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

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

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

            
            if (filter.teaching_type) {
                where = {
                    ...where,
                teaching_type: filter.teaching_type,
            };
            }
            
            if (filter.session_language) {
                where = {
                    ...where,
                session_language: filter.session_language,
            };
            }
            
            if (filter.teaching_format) {
                where = {
                    ...where,
                teaching_format: filter.teaching_format,
            };
            }
            
            if (filter.verification_status) {
                where = {
                    ...where,
                verification_status: filter.verification_status,
            };
            }
            
            if (filter.badge_level) {
                where = {
                    ...where,
                badge_level: filter.badge_level,
            };
            }
            
            if (filter.vacation_mode) {
                where = {
                    ...where,
                vacation_mode: filter.vacation_mode,
            };
            }
            


      


      if (filter.subject_categories) {
        const searchTerms = filter.subject_categories.split('|');

        include = [
          {
            model: db.subject_categories,
            as: 'subject_categories_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name_en: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.subjects) {
        const searchTerms = filter.subjects.split('|');

        include = [
          {
            model: db.subjects,
            as: 'subjects_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.languages) {
        const searchTerms = filter.languages.split('|');

        include = [
          {
            model: db.languages,
            as: 'languages_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

