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

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

        const legal_sources = await db.legal_sources.create(
            {
                id: data.id || undefined,
        
        source_type: data.source_type
        ||
        null
            ,
            
        jurisdiction: data.jurisdiction
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        citation: data.citation
        ||
        null
            ,
            
        decision_date: data.decision_date
        ||
        null
            ,
            
        court: data.court
        ||
        null
            ,
            
        full_text: data.full_text
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        source_url: data.source_url
        ||
        null
            ,
            
        last_updated_at: data.last_updated_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return legal_sources;
    }
    

    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 legal_sourcesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                source_type: item.source_type
            ||
            null
            ,
            
                jurisdiction: item.jurisdiction
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                citation: item.citation
            ||
            null
            ,
            
                decision_date: item.decision_date
            ||
            null
            ,
            
                court: item.court
            ||
            null
            ,
            
                full_text: item.full_text
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                source_url: item.source_url
            ||
            null
            ,
            
                last_updated_at: item.last_updated_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return legal_sources;
    }

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

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


        

        const updatePayload = {};
        
        if (data.source_type !== undefined) updatePayload.source_type = data.source_type;
        
        
        if (data.jurisdiction !== undefined) updatePayload.jurisdiction = data.jurisdiction;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.citation !== undefined) updatePayload.citation = data.citation;
        
        
        if (data.decision_date !== undefined) updatePayload.decision_date = data.decision_date;
        
        
        if (data.court !== undefined) updatePayload.court = data.court;
        
        
        if (data.full_text !== undefined) updatePayload.full_text = data.full_text;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.source_url !== undefined) updatePayload.source_url = data.source_url;
        
        
        if (data.last_updated_at !== undefined) updatePayload.last_updated_at = data.last_updated_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return legal_sources;
    }

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

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

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


        return legal_sources;
    }

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

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

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

        await legal_sources.destroy({
            transaction
        });

        return legal_sources;
    }

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

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

        if (!legal_sources) {
            return legal_sources;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.research_results_legal_source = await legal_sources.getResearch_results_legal_source({
            transaction
        });
        
        
        output.citator_checks_legal_source = await legal_sources.getCitator_checks_legal_source({
            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 = [



    ];

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

            
            if (filter.jurisdiction) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'legal_sources',
                        'jurisdiction',
                        filter.jurisdiction,
                    ),
                };
            }
            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'legal_sources',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.citation) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'legal_sources',
                        'citation',
                        filter.citation,
                    ),
                };
            }
            
            if (filter.court) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'legal_sources',
                        'court',
                        filter.court,
                    ),
                };
            }
            
            if (filter.full_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'legal_sources',
                        'full_text',
                        filter.full_text,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'legal_sources',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            
            if (filter.source_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'legal_sources',
                        'source_url',
                        filter.source_url,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    last_updated_at: {
                    ...where.last_updated_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.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.legal_sources.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(
                        'legal_sources',
                        'title',
                        query,
                    ),
                ],
            };
        }

        const records = await db.legal_sources.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,
        }));
    }

    
};

