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

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

        const festival_attendance = await db.festival_attendance.create(
            {
                id: data.id || undefined,
        
        attendance_role: data.attendance_role
        ||
        null
            ,
            
        did_attend: data.did_attend
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await festival_attendance.setFestival( data.festival || null, {
            transaction,
        });
        
        await festival_attendance.setNpc( data.npc || null, {
            transaction,
        });
        

        

        

        return festival_attendance;
    }
    

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

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

        // For each item created, replace relation files
        

        return festival_attendance;
    }

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

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


        

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

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

        
        
        if (data.festival !== undefined) {
            await festival_attendance.setFestival(
              
              data.festival,
              
              { transaction }
            );
        }
        
        if (data.npc !== undefined) {
            await festival_attendance.setNpc(
              
              data.npc,
              
              { transaction }
            );
        }
        

        
        

        

        return festival_attendance;
    }

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

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

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


        return festival_attendance;
    }

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

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

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

        await festival_attendance.destroy({
            transaction
        });

        return festival_attendance;
    }

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

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

        if (!festival_attendance) {
            return festival_attendance;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.festival = await festival_attendance.getFestival({
            transaction
        });
        
        
        output.npc = await festival_attendance.getNpc({
            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.festivals,
        as: 'festival',
        
        where: filter.festival ? {
          [Op.or]: [
            { id: { [Op.in]: filter.festival.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.festival.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            

            

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

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


      

      



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

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

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

    
};

