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

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

        const seed_votes = await db.seed_votes.create(
            {
                id: data.id || undefined,
        
        direction: data.direction
        ||
        null
            ,
            
        voted_at: data.voted_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await seed_votes.setClub( data.club || null, {
            transaction,
        });
        
        await seed_votes.setVoter_user( data.voter_user || null, {
            transaction,
        });
        
        await seed_votes.setTarget_player( data.target_player || null, {
            transaction,
        });
        
        await seed_votes.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return seed_votes;
    }
    

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

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

        // For each item created, replace relation files
        

        return seed_votes;
    }

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

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


        

        const updatePayload = {};
        
        if (data.direction !== undefined) updatePayload.direction = data.direction;
        
        
        if (data.voted_at !== undefined) updatePayload.voted_at = data.voted_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.club !== undefined) {
            await seed_votes.setClub(
              
              data.club,
              
              { transaction }
            );
        }
        
        if (data.voter_user !== undefined) {
            await seed_votes.setVoter_user(
              
              data.voter_user,
              
              { transaction }
            );
        }
        
        if (data.target_player !== undefined) {
            await seed_votes.setTarget_player(
              
              data.target_player,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await seed_votes.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return seed_votes;
    }

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

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

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


        return seed_votes;
    }

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

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

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

        await seed_votes.destroy({
            transaction
        });

        return seed_votes;
    }

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

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

        if (!seed_votes) {
            return seed_votes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.club = await seed_votes.getClub({
            transaction
        });
        
        
        output.voter_user = await seed_votes.getVoter_user({
            transaction
        });
        
        
        output.target_player = await seed_votes.getTarget_player({
            transaction
        });
        
        
        output.organizations = await seed_votes.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            

            
            

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

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

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

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

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


      

      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.seed_votes.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'seed_votes',
                        'direction',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

