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

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

        const book_clubs = await db.book_clubs.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        visibility: data.visibility
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        created_at_time: data.created_at_time
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await book_clubs.setOwner( data.owner || null, {
            transaction,
        });
        

        

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

        return book_clubs;
    }
    

    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 book_clubsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                visibility: item.visibility
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                created_at_time: item.created_at_time
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return book_clubs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.created_at_time !== undefined) updatePayload.created_at_time = data.created_at_time;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner !== undefined) {
            await book_clubs.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        

        
        

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

        return book_clubs;
    }

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

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

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


        return book_clubs;
    }

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

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

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

        await book_clubs.destroy({
            transaction
        });

        return book_clubs;
    }

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

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

        if (!book_clubs) {
            return book_clubs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.book_club_memberships_book_club = await book_clubs.getBook_club_memberships_book_club({
            transaction
        });
        
        
        output.club_chat_messages_book_club = await book_clubs.getClub_chat_messages_book_club({
            transaction
        });
        
        
        output.reading_circle_events_book_club = await book_clubs.getReading_circle_events_book_club({
            transaction
        });
        
        
        
        
        
        
        
        
        output.cover_images = await book_clubs.getCover_images({
            transaction
        });
        
        
        output.owner = await book_clubs.getOwner({
            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.users,
        as: 'owner',
        
        where: filter.owner ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

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

            
            

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

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

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

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

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


      



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

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

    
};

