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

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

        const leagues = await db.leagues.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        season_label: data.season_label
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        rosters_locked: data.rosters_locked
        ||
        false
        
            ,
            
        registration_fee: data.registration_fee
        ||
        null
            ,
            
        rules_notes: data.rules_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await leagues.setClub( data.club || null, {
            transaction,
        });
        
        await leagues.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return leagues;
    }
    

    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 leaguesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                season_label: item.season_label
            ||
            null
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                rosters_locked: item.rosters_locked
            ||
            false
        
            ,
            
                registration_fee: item.registration_fee
            ||
            null
            ,
            
                rules_notes: item.rules_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return leagues;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.season_label !== undefined) updatePayload.season_label = data.season_label;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.rosters_locked !== undefined) updatePayload.rosters_locked = data.rosters_locked;
        
        
        if (data.registration_fee !== undefined) updatePayload.registration_fee = data.registration_fee;
        
        
        if (data.rules_notes !== undefined) updatePayload.rules_notes = data.rules_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.club !== undefined) {
            await leagues.setClub(
              
              data.club,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await leagues.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return leagues;
    }

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

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

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


        return leagues;
    }

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

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

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

        await leagues.destroy({
            transaction
        });

        return leagues;
    }

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

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

        if (!leagues) {
            return leagues;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.league_teams_league = await leagues.getLeague_teams_league({
            transaction
        });
        
        
        
        output.games_league = await leagues.getGames_league({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.league_payments_league = await leagues.getLeague_payments_league({
            transaction
        });
        
        
        output.league_standings_league = await leagues.getLeague_standings_league({
            transaction
        });
        
        
        output.league_finish_awards_league = await leagues.getLeague_finish_awards_league({
            transaction
        });
        
        
        
        
        
        output.club = await leagues.getClub({
            transaction
        });
        
        
        output.organizations = await leagues.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.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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


      

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

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

    
};

