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

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

        const gallery_items = await db.gallery_items.create(
            {
                id: data.id || undefined,
        
        caption: data.caption
        ||
        null
            ,
            
        alt_text: data.alt_text
        ||
        null
            ,
            
        sort_order: data.sort_order
        ||
        null
            ,
            
        is_featured: data.is_featured
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await gallery_items.setGallery( data.gallery || null, {
            transaction,
        });
        

        

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

        return gallery_items;
    }
    

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

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

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

        return gallery_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.caption !== undefined) updatePayload.caption = data.caption;
        
        
        if (data.alt_text !== undefined) updatePayload.alt_text = data.alt_text;
        
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        if (data.is_featured !== undefined) updatePayload.is_featured = data.is_featured;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.gallery !== undefined) {
            await gallery_items.setGallery(
              
              data.gallery,
              
              { transaction }
            );
        }
        

        
        

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

        return gallery_items;
    }

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

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

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


        return gallery_items;
    }

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

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

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

        await gallery_items.destroy({
            transaction
        });

        return gallery_items;
    }

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

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

        if (!gallery_items) {
            return gallery_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.gallery = await gallery_items.getGallery({
            transaction
        });
        
        
        output.image = await gallery_items.getImage({
            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.galleries,
        as: 'gallery',
        
        where: filter.gallery ? {
          [Op.or]: [
            { id: { [Op.in]: filter.gallery.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.gallery.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.caption) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'gallery_items',
                        'caption',
                        filter.caption,
                    ),
                };
            }
            
            if (filter.alt_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'gallery_items',
                        'alt_text',
                        filter.alt_text,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      



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

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

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

    
};

