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

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

        const flashcards = await db.flashcards.create(
            {
                id: data.id || undefined,
        
        front: data.front
        ||
        null
            ,
            
        back: data.back
        ||
        null
            ,
            
        hint: data.hint
        ||
        null
            ,
            
        card_type: data.card_type
        ||
        null
            ,
            
        sort_order: data.sort_order
        ||
        null
            ,
            
        is_suspended: data.is_suspended
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await flashcards.setDeck( data.deck || null, {
            transaction,
        });
        
        await flashcards.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return flashcards;
    }
    

    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 flashcardsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                front: item.front
            ||
            null
            ,
            
                back: item.back
            ||
            null
            ,
            
                hint: item.hint
            ||
            null
            ,
            
                card_type: item.card_type
            ||
            null
            ,
            
                sort_order: item.sort_order
            ||
            null
            ,
            
                is_suspended: item.is_suspended
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return flashcards;
    }

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


        

        const updatePayload = {};
        
        if (data.front !== undefined) updatePayload.front = data.front;
        
        
        if (data.back !== undefined) updatePayload.back = data.back;
        
        
        if (data.hint !== undefined) updatePayload.hint = data.hint;
        
        
        if (data.card_type !== undefined) updatePayload.card_type = data.card_type;
        
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        if (data.is_suspended !== undefined) updatePayload.is_suspended = data.is_suspended;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.deck !== undefined) {
            await flashcards.setDeck(
              
              data.deck,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await flashcards.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return flashcards;
    }

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

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

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


        return flashcards;
    }

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

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

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

        await flashcards.destroy({
            transaction
        });

        return flashcards;
    }

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

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

        if (!flashcards) {
            return flashcards;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.spaced_repetition_states_flashcard = await flashcards.getSpaced_repetition_states_flashcard({
            transaction
        });
        
        
        
        output.review_events_flashcard = await flashcards.getReview_events_flashcard({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.deck = await flashcards.getDeck({
            transaction
        });
        
        
        output.image = await flashcards.getImage({
            transaction
        });
        
        
        output.organizations = await flashcards.getOrganizations({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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



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

    ];

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

            
            if (filter.front) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'flashcards',
                        'front',
                        filter.front,
                    ),
                };
            }
            
            if (filter.back) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'flashcards',
                        'back',
                        filter.back,
                    ),
                };
            }
            
            if (filter.hint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'flashcards',
                        'hint',
                        filter.hint,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.card_type) {
                where = {
                    ...where,
                card_type: filter.card_type,
            };
            }
            
            if (filter.is_suspended) {
                where = {
                    ...where,
                is_suspended: filter.is_suspended,
            };
            }
            


      

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

        where = {
          ...where,
          organizationsId: {[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.organizationsId;
        }
        

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

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

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

    
};

