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

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

        const study_materials = await db.study_materials.create(
            {
                id: data.id || undefined,
        
        title_om: data.title_om
        ||
        null
            ,
            
        title_am: data.title_am
        ||
        null
            ,
            
        title_en: data.title_en
        ||
        null
            ,
            
        material_type: data.material_type
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        external_url: data.external_url
        ||
        null
            ,
            
        visibility: data.visibility
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await study_materials.setGrade( data.grade || null, {
            transaction,
        });
        
        await study_materials.setSubject( data.subject || null, {
            transaction,
        });
        
        await study_materials.setStream( data.stream || null, {
            transaction,
        });
        
        await study_materials.setUploaded_by( data.uploaded_by || null, {
            transaction,
        });
        

        

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

        return study_materials;
    }
    

    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 study_materialsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title_om: item.title_om
            ||
            null
            ,
            
                title_am: item.title_am
            ||
            null
            ,
            
                title_en: item.title_en
            ||
            null
            ,
            
                material_type: item.material_type
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                external_url: item.external_url
            ||
            null
            ,
            
                visibility: item.visibility
            ||
            null
            ,
            
                published_at: item.published_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return study_materials;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title_om !== undefined) updatePayload.title_om = data.title_om;
        
        
        if (data.title_am !== undefined) updatePayload.title_am = data.title_am;
        
        
        if (data.title_en !== undefined) updatePayload.title_en = data.title_en;
        
        
        if (data.material_type !== undefined) updatePayload.material_type = data.material_type;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.external_url !== undefined) updatePayload.external_url = data.external_url;
        
        
        if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.grade !== undefined) {
            await study_materials.setGrade(
              
              data.grade,
              
              { transaction }
            );
        }
        
        if (data.subject !== undefined) {
            await study_materials.setSubject(
              
              data.subject,
              
              { transaction }
            );
        }
        
        if (data.stream !== undefined) {
            await study_materials.setStream(
              
              data.stream,
              
              { transaction }
            );
        }
        
        if (data.uploaded_by !== undefined) {
            await study_materials.setUploaded_by(
              
              data.uploaded_by,
              
              { transaction }
            );
        }
        

        
        

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

        return study_materials;
    }

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

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

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


        return study_materials;
    }

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

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

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

        await study_materials.destroy({
            transaction
        });

        return study_materials;
    }

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

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

        if (!study_materials) {
            return study_materials;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.grade = await study_materials.getGrade({
            transaction
        });
        
        
        output.subject = await study_materials.getSubject({
            transaction
        });
        
        
        output.stream = await study_materials.getStream({
            transaction
        });
        
        
        output.file = await study_materials.getFile({
            transaction
        });
        
        
        output.uploaded_by = await study_materials.getUploaded_by({
            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.grades,
        as: 'grade',
        
        where: filter.grade ? {
          [Op.or]: [
            { id: { [Op.in]: filter.grade.split('|').map(term => Utils.uuid(term)) } },
            {
              label: {
                [Op.or]: filter.grade.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



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

    ];

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

            
            if (filter.title_om) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'study_materials',
                        'title_om',
                        filter.title_om,
                    ),
                };
            }
            
            if (filter.title_am) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'study_materials',
                        'title_am',
                        filter.title_am,
                    ),
                };
            }
            
            if (filter.title_en) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'study_materials',
                        'title_en',
                        filter.title_en,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'study_materials',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.external_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'study_materials',
                        'external_url',
                        filter.external_url,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.material_type) {
                where = {
                    ...where,
                material_type: filter.material_type,
            };
            }
            
            if (filter.visibility) {
                where = {
                    ...where,
                visibility: filter.visibility,
            };
            }
            


      

      

      

      



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

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

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

    
};

