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

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

        const league_standings = await db.league_standings.create(
            {
                id: data.id || undefined,
        
        played: data.played
        ||
        null
            ,
            
        wins: data.wins
        ||
        null
            ,
            
        draws: data.draws
        ||
        null
            ,
            
        losses: data.losses
        ||
        null
            ,
            
        goals_for: data.goals_for
        ||
        null
            ,
            
        goals_against: data.goals_against
        ||
        null
            ,
            
        goal_difference: data.goal_difference
        ||
        null
            ,
            
        points: data.points
        ||
        null
            ,
            
        rank: data.rank
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await league_standings.setLeague( data.league || null, {
            transaction,
        });
        
        await league_standings.setLeague_team( data.league_team || null, {
            transaction,
        });
        
        await league_standings.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return league_standings;
    }
    

    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 league_standingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                played: item.played
            ||
            null
            ,
            
                wins: item.wins
            ||
            null
            ,
            
                draws: item.draws
            ||
            null
            ,
            
                losses: item.losses
            ||
            null
            ,
            
                goals_for: item.goals_for
            ||
            null
            ,
            
                goals_against: item.goals_against
            ||
            null
            ,
            
                goal_difference: item.goal_difference
            ||
            null
            ,
            
                points: item.points
            ||
            null
            ,
            
                rank: item.rank
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return league_standings;
    }

    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 league_standings = await db.league_standings.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.played !== undefined) updatePayload.played = data.played;
        
        
        if (data.wins !== undefined) updatePayload.wins = data.wins;
        
        
        if (data.draws !== undefined) updatePayload.draws = data.draws;
        
        
        if (data.losses !== undefined) updatePayload.losses = data.losses;
        
        
        if (data.goals_for !== undefined) updatePayload.goals_for = data.goals_for;
        
        
        if (data.goals_against !== undefined) updatePayload.goals_against = data.goals_against;
        
        
        if (data.goal_difference !== undefined) updatePayload.goal_difference = data.goal_difference;
        
        
        if (data.points !== undefined) updatePayload.points = data.points;
        
        
        if (data.rank !== undefined) updatePayload.rank = data.rank;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.league !== undefined) {
            await league_standings.setLeague(
              
              data.league,
              
              { transaction }
            );
        }
        
        if (data.league_team !== undefined) {
            await league_standings.setLeague_team(
              
              data.league_team,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await league_standings.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return league_standings;
    }

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

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

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


        return league_standings;
    }

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

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

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

        await league_standings.destroy({
            transaction
        });

        return league_standings;
    }

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

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

        if (!league_standings) {
            return league_standings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.league = await league_standings.getLeague({
            transaction
        });
        
        
        output.league_team = await league_standings.getLeague_team({
            transaction
        });
        
        
        output.organizations = await league_standings.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.leagues,
        as: 'league',
        
        where: filter.league ? {
          [Op.or]: [
            { id: { [Op.in]: filter.league.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.league.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.league_teams,
        as: 'league_team',
        
        where: filter.league_team ? {
          [Op.or]: [
            { id: { [Op.in]: filter.league_team.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.league_team.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.playedRange) {
                const [start, end] = filter.playedRange;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            


      

      

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

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

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

    
};

