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

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

        const citations = await db.citations.create(
            {
                id: data.id || undefined,
        
        source_type: data.source_type
        ||
        null
            ,
            
        source_title: data.source_title
        ||
        null
            ,
            
        source_url: data.source_url
        ||
        null
            ,
            
        publisher: data.publisher
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
        quote_excerpt: data.quote_excerpt
        ||
        null
            ,
            
        doi_or_identifier: data.doi_or_identifier
        ||
        null
            ,
            
        credibility_grade: data.credibility_grade
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await citations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return citations;
    }
    

    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 citationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                source_type: item.source_type
            ||
            null
            ,
            
                source_title: item.source_title
            ||
            null
            ,
            
                source_url: item.source_url
            ||
            null
            ,
            
                publisher: item.publisher
            ||
            null
            ,
            
                published_at: item.published_at
            ||
            null
            ,
            
                quote_excerpt: item.quote_excerpt
            ||
            null
            ,
            
                doi_or_identifier: item.doi_or_identifier
            ||
            null
            ,
            
                credibility_grade: item.credibility_grade
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return citations;
    }

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


        

        const updatePayload = {};
        
        if (data.source_type !== undefined) updatePayload.source_type = data.source_type;
        
        
        if (data.source_title !== undefined) updatePayload.source_title = data.source_title;
        
        
        if (data.source_url !== undefined) updatePayload.source_url = data.source_url;
        
        
        if (data.publisher !== undefined) updatePayload.publisher = data.publisher;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        if (data.quote_excerpt !== undefined) updatePayload.quote_excerpt = data.quote_excerpt;
        
        
        if (data.doi_or_identifier !== undefined) updatePayload.doi_or_identifier = data.doi_or_identifier;
        
        
        if (data.credibility_grade !== undefined) updatePayload.credibility_grade = data.credibility_grade;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return citations;
    }

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

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

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


        return citations;
    }

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

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

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

        await citations.destroy({
            transaction
        });

        return citations;
    }

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

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

        if (!citations) {
            return citations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organizations = await citations.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.source_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'citations',
                        'source_title',
                        filter.source_title,
                    ),
                };
            }
            
            if (filter.source_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'citations',
                        'source_url',
                        filter.source_url,
                    ),
                };
            }
            
            if (filter.publisher) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'citations',
                        'publisher',
                        filter.publisher,
                    ),
                };
            }
            
            if (filter.quote_excerpt) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'citations',
                        'quote_excerpt',
                        filter.quote_excerpt,
                    ),
                };
            }
            
            if (filter.doi_or_identifier) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'citations',
                        'doi_or_identifier',
                        filter.doi_or_identifier,
                    ),
                };
            }
            

            
            

            
            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.source_type) {
                where = {
                    ...where,
                source_type: filter.source_type,
            };
            }
            
            if (filter.credibility_grade) {
                where = {
                    ...where,
                credibility_grade: filter.credibility_grade,
            };
            }
            


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

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

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

    
};

