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

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

        const fishing_catches = await db.fishing_catches.create(
            {
                id: data.id || undefined,
        
        caught_at: data.caught_at
        ||
        null
            ,
            
        weight: data.weight
        ||
        null
            ,
            
        length: data.length
        ||
        null
            ,
            
        quality_grade: data.quality_grade
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await fishing_catches.setPlayer_profile( data.player_profile || null, {
            transaction,
        });
        
        await fishing_catches.setFishing_spot( data.fishing_spot || null, {
            transaction,
        });
        
        await fishing_catches.setFish_species( data.fish_species || null, {
            transaction,
        });
        

        

        

        return fishing_catches;
    }
    

    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 fishing_catchesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                caught_at: item.caught_at
            ||
            null
            ,
            
                weight: item.weight
            ||
            null
            ,
            
                length: item.length
            ||
            null
            ,
            
                quality_grade: item.quality_grade
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return fishing_catches;
    }

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

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


        

        const updatePayload = {};
        
        if (data.caught_at !== undefined) updatePayload.caught_at = data.caught_at;
        
        
        if (data.weight !== undefined) updatePayload.weight = data.weight;
        
        
        if (data.length !== undefined) updatePayload.length = data.length;
        
        
        if (data.quality_grade !== undefined) updatePayload.quality_grade = data.quality_grade;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.player_profile !== undefined) {
            await fishing_catches.setPlayer_profile(
              
              data.player_profile,
              
              { transaction }
            );
        }
        
        if (data.fishing_spot !== undefined) {
            await fishing_catches.setFishing_spot(
              
              data.fishing_spot,
              
              { transaction }
            );
        }
        
        if (data.fish_species !== undefined) {
            await fishing_catches.setFish_species(
              
              data.fish_species,
              
              { transaction }
            );
        }
        

        
        

        

        return fishing_catches;
    }

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

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

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


        return fishing_catches;
    }

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

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

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

        await fishing_catches.destroy({
            transaction
        });

        return fishing_catches;
    }

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

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

        if (!fishing_catches) {
            return fishing_catches;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.player_profile = await fishing_catches.getPlayer_profile({
            transaction
        });
        
        
        output.fishing_spot = await fishing_catches.getFishing_spot({
            transaction
        });
        
        
        output.fish_species = await fishing_catches.getFish_species({
            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.player_profiles,
        as: 'player_profile',
        
        where: filter.player_profile ? {
          [Op.or]: [
            { id: { [Op.in]: filter.player_profile.split('|').map(term => Utils.uuid(term)) } },
            {
              first_name: {
                [Op.or]: filter.player_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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


      

      

      



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

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

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

    
};

