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

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

        const fish_species = await db.fish_species.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        rarity: data.rarity
        ||
        null
            ,
            
        active_time: data.active_time
        ||
        null
            ,
            
        preferred_weather: data.preferred_weather
        ||
        null
            ,
            
        base_bite_rate: data.base_bite_rate
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await fish_species.setItem( data.item || null, {
            transaction,
        });
        

        

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

        return fish_species;
    }
    

    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 fish_speciesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                rarity: item.rarity
            ||
            null
            ,
            
                active_time: item.active_time
            ||
            null
            ,
            
                preferred_weather: item.preferred_weather
            ||
            null
            ,
            
                base_bite_rate: item.base_bite_rate
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return fish_species;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.rarity !== undefined) updatePayload.rarity = data.rarity;
        
        
        if (data.active_time !== undefined) updatePayload.active_time = data.active_time;
        
        
        if (data.preferred_weather !== undefined) updatePayload.preferred_weather = data.preferred_weather;
        
        
        if (data.base_bite_rate !== undefined) updatePayload.base_bite_rate = data.base_bite_rate;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.item !== undefined) {
            await fish_species.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        

        
        

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

        return fish_species;
    }

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

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

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


        return fish_species;
    }

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

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

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

        await fish_species.destroy({
            transaction
        });

        return fish_species;
    }

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

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

        if (!fish_species) {
            return fish_species;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.fishing_catches_fish_species = await fish_species.getFishing_catches_fish_species({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.item = await fish_species.getItem({
            transaction
        });
        
        
        output.fish_images = await fish_species.getFish_images({
            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 = [

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



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

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'fish_species',
                        'name',
                        filter.name,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.rarity) {
                where = {
                    ...where,
                rarity: filter.rarity,
            };
            }
            
            if (filter.active_time) {
                where = {
                    ...where,
                active_time: filter.active_time,
            };
            }
            
            if (filter.preferred_weather) {
                where = {
                    ...where,
                preferred_weather: filter.preferred_weather,
            };
            }
            


      



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

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

    
};

