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

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

        const media_library = await db.media_library.create(
            {
                id: data.id || undefined,
        
        media_type: data.media_type
        ||
        null
            ,
            
        title_ar: data.title_ar
        ||
        null
            ,
            
        alt_text_ar: data.alt_text_ar
        ||
        null
            ,
            
        source_note_ar: data.source_note_ar
        ||
        null
            ,
            
        is_public: data.is_public
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

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

        return media_library;
    }
    

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

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

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

        return media_library;
    }

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

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


        

        const updatePayload = {};
        
        if (data.media_type !== undefined) updatePayload.media_type = data.media_type;
        
        
        if (data.title_ar !== undefined) updatePayload.title_ar = data.title_ar;
        
        
        if (data.alt_text_ar !== undefined) updatePayload.alt_text_ar = data.alt_text_ar;
        
        
        if (data.source_note_ar !== undefined) updatePayload.source_note_ar = data.source_note_ar;
        
        
        if (data.is_public !== undefined) updatePayload.is_public = data.is_public;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

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

        return media_library;
    }

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

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

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


        return media_library;
    }

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

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

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

        await media_library.destroy({
            transaction
        });

        return media_library;
    }

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

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

        if (!media_library) {
            return media_library;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.images = await media_library.getImages({
            transaction
        });
        
        
        output.files = await media_library.getFiles({
            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.file,
        as: 'images',
      },

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

    ];

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

            
            if (filter.title_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'media_library',
                        'title_ar',
                        filter.title_ar,
                    ),
                };
            }
            
            if (filter.alt_text_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'media_library',
                        'alt_text_ar',
                        filter.alt_text_ar,
                    ),
                };
            }
            
            if (filter.source_note_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'media_library',
                        'source_note_ar',
                        filter.source_note_ar,
                    ),
                };
            }
            

            
            

            

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

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




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

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

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

    
};

