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

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

        const user_stories = await db.user_stories.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        as_a: data.as_a
        ||
        null
            ,
            
        i_want: data.i_want
        ||
        null
            ,
            
        so_that: data.so_that
        ||
        null
            ,
            
        template_type: data.template_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        board_column: data.board_column
        ||
        null
            ,
            
        priority: data.priority
        ||
        null
            ,
            
        quality_score: data.quality_score
        ||
        null
            ,
            
        quality_suggestions: data.quality_suggestions
        ||
        null
            ,
            
        tags_csv: data.tags_csv
        ||
        null
            ,
            
        created_at_time: data.created_at_time
        ||
        null
            ,
            
        updated_at_time: data.updated_at_time
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await user_stories.setTeam( data.team || null, {
            transaction,
        });
        
        await user_stories.setAssignee( data.assignee || null, {
            transaction,
        });
        
        await user_stories.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return user_stories;
    }
    

    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 user_storiesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                as_a: item.as_a
            ||
            null
            ,
            
                i_want: item.i_want
            ||
            null
            ,
            
                so_that: item.so_that
            ||
            null
            ,
            
                template_type: item.template_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                board_column: item.board_column
            ||
            null
            ,
            
                priority: item.priority
            ||
            null
            ,
            
                quality_score: item.quality_score
            ||
            null
            ,
            
                quality_suggestions: item.quality_suggestions
            ||
            null
            ,
            
                tags_csv: item.tags_csv
            ||
            null
            ,
            
                created_at_time: item.created_at_time
            ||
            null
            ,
            
                updated_at_time: item.updated_at_time
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return user_stories;
    }

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.as_a !== undefined) updatePayload.as_a = data.as_a;
        
        
        if (data.i_want !== undefined) updatePayload.i_want = data.i_want;
        
        
        if (data.so_that !== undefined) updatePayload.so_that = data.so_that;
        
        
        if (data.template_type !== undefined) updatePayload.template_type = data.template_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.board_column !== undefined) updatePayload.board_column = data.board_column;
        
        
        if (data.priority !== undefined) updatePayload.priority = data.priority;
        
        
        if (data.quality_score !== undefined) updatePayload.quality_score = data.quality_score;
        
        
        if (data.quality_suggestions !== undefined) updatePayload.quality_suggestions = data.quality_suggestions;
        
        
        if (data.tags_csv !== undefined) updatePayload.tags_csv = data.tags_csv;
        
        
        if (data.created_at_time !== undefined) updatePayload.created_at_time = data.created_at_time;
        
        
        if (data.updated_at_time !== undefined) updatePayload.updated_at_time = data.updated_at_time;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.team !== undefined) {
            await user_stories.setTeam(
              
              data.team,
              
              { transaction }
            );
        }
        
        if (data.assignee !== undefined) {
            await user_stories.setAssignee(
              
              data.assignee,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await user_stories.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return user_stories;
    }

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

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

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


        return user_stories;
    }

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

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

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

        await user_stories.destroy({
            transaction
        });

        return user_stories;
    }

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

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

        if (!user_stories) {
            return user_stories;
        }

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

        
        
        
        
        
        
        
        
        
        output.acceptance_criteria_story = await user_stories.getAcceptance_criteria_story({
            transaction
        });
        
        
        
        
        
        output.story_document_links_story = await user_stories.getStory_document_links_story({
            transaction
        });
        
        
        output.collaboration_sessions_story = await user_stories.getCollaboration_sessions_story({
            transaction
        });
        
        
        output.comment_threads_story = await user_stories.getComment_threads_story({
            transaction
        });
        
        
        
        
        
        
        output.approvals_story = await user_stories.getApprovals_story({
            transaction
        });
        
        
        
        
        
        
        output.sprint_items_story = await user_stories.getSprint_items_story({
            transaction
        });
        
        
        output.blockers_story = await user_stories.getBlockers_story({
            transaction
        });
        
        
        
        output.ai_generations_story = await user_stories.getAi_generations_story({
            transaction
        });
        
        
        
        output.team = await user_stories.getTeam({
            transaction
        });
        
        
        output.assignee = await user_stories.getAssignee({
            transaction
        });
        
        
        output.organizations = await user_stories.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.teams,
        as: 'team',
        
        where: filter.team ? {
          [Op.or]: [
            { id: { [Op.in]: filter.team.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.team.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_stories',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.as_a) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_stories',
                        'as_a',
                        filter.as_a,
                    ),
                };
            }
            
            if (filter.i_want) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_stories',
                        'i_want',
                        filter.i_want,
                    ),
                };
            }
            
            if (filter.so_that) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_stories',
                        'so_that',
                        filter.so_that,
                    ),
                };
            }
            
            if (filter.quality_suggestions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_stories',
                        'quality_suggestions',
                        filter.quality_suggestions,
                    ),
                };
            }
            
            if (filter.tags_csv) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'user_stories',
                        'tags_csv',
                        filter.tags_csv,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.template_type) {
                where = {
                    ...where,
                template_type: filter.template_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.board_column) {
                where = {
                    ...where,
                board_column: filter.board_column,
            };
            }
            
            if (filter.priority) {
                where = {
                    ...where,
                priority: filter.priority,
            };
            }
            


      

      

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

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

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

    
};

