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

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

        const fishing_spots = await db.fishing_spots.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        water_type: data.water_type
        ||
        null
            ,
            
        difficulty_rating: data.difficulty_rating
        ||
        null
            ,
            
        is_tournament_site: data.is_tournament_site
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await fishing_spots.setLocation( data.location || null, {
            transaction,
        });
        

        

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

        return fishing_spots;
    }
    

    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_spotsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                water_type: item.water_type
            ||
            null
            ,
            
                difficulty_rating: item.difficulty_rating
            ||
            null
            ,
            
                is_tournament_site: item.is_tournament_site
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return fishing_spots;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.water_type !== undefined) updatePayload.water_type = data.water_type;
        
        
        if (data.difficulty_rating !== undefined) updatePayload.difficulty_rating = data.difficulty_rating;
        
        
        if (data.is_tournament_site !== undefined) updatePayload.is_tournament_site = data.is_tournament_site;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.location !== undefined) {
            await fishing_spots.setLocation(
              
              data.location,
              
              { transaction }
            );
        }
        

        
        

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

        return fishing_spots;
    }

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

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

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


        return fishing_spots;
    }

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

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

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

        await fishing_spots.destroy({
            transaction
        });

        return fishing_spots;
    }

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

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

        if (!fishing_spots) {
            return fishing_spots;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.fishing_catches_fishing_spot = await fishing_spots.getFishing_catches_fishing_spot({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.location = await fishing_spots.getLocation({
            transaction
        });
        
        
        output.spot_images = await fishing_spots.getSpot_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.locations,
        as: 'location',
        
        where: filter.location ? {
          [Op.or]: [
            { id: { [Op.in]: filter.location.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

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

            
            

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

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

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

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

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


      



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

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

    
};

