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

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

        const field_trip_catalog = await db.field_trip_catalog.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        location_name: data.location_name
        ||
        null
            ,
            
        grade_range: data.grade_range
        ||
        null
            ,
            
        typical_min_rate: data.typical_min_rate
        ||
        null
            ,
            
        typical_max_rate: data.typical_max_rate
        ||
        null
            ,
            
        separate_payment_required: data.separate_payment_required
        ||
        false
        
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return field_trip_catalog;
    }
    

    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 field_trip_catalogData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                category: item.category
            ||
            null
            ,
            
                location_name: item.location_name
            ||
            null
            ,
            
                grade_range: item.grade_range
            ||
            null
            ,
            
                typical_min_rate: item.typical_min_rate
            ||
            null
            ,
            
                typical_max_rate: item.typical_max_rate
            ||
            null
            ,
            
                separate_payment_required: item.separate_payment_required
            ||
            false
        
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return field_trip_catalog;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.location_name !== undefined) updatePayload.location_name = data.location_name;
        
        
        if (data.grade_range !== undefined) updatePayload.grade_range = data.grade_range;
        
        
        if (data.typical_min_rate !== undefined) updatePayload.typical_min_rate = data.typical_min_rate;
        
        
        if (data.typical_max_rate !== undefined) updatePayload.typical_max_rate = data.typical_max_rate;
        
        
        if (data.separate_payment_required !== undefined) updatePayload.separate_payment_required = data.separate_payment_required;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return field_trip_catalog;
    }

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

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

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


        return field_trip_catalog;
    }

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

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

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

        await field_trip_catalog.destroy({
            transaction
        });

        return field_trip_catalog;
    }

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

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

        if (!field_trip_catalog) {
            return field_trip_catalog;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.field_trip_events_field_trip = await field_trip_catalog.getField_trip_events_field_trip({
            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.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'field_trip_catalog',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.location_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'field_trip_catalog',
                        'location_name',
                        filter.location_name,
                    ),
                };
            }
            
            if (filter.grade_range) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'field_trip_catalog',
                        'grade_range',
                        filter.grade_range,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'field_trip_catalog',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.category) {
                where = {
                    ...where,
                category: filter.category,
            };
            }
            
            if (filter.separate_payment_required) {
                where = {
                    ...where,
                separate_payment_required: filter.separate_payment_required,
            };
            }
            




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

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

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

    
};

