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

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

        const project_media = await db.project_media.create(
            {
                id: data.id || undefined,
        
        media_kind: data.media_kind
        ||
        null
            ,
            
        media_role: data.media_role
        ||
        null
            ,
            
        caption_ar: data.caption_ar
        ||
        null
            ,
            
        sort_order: data.sort_order
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await project_media.setProject( data.project || null, {
            transaction,
        });
        

        

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

        return project_media;
    }
    

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

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

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

        return project_media;
    }

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

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


        

        const updatePayload = {};
        
        if (data.media_kind !== undefined) updatePayload.media_kind = data.media_kind;
        
        
        if (data.media_role !== undefined) updatePayload.media_role = data.media_role;
        
        
        if (data.caption_ar !== undefined) updatePayload.caption_ar = data.caption_ar;
        
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await project_media.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        

        
        

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

        return project_media;
    }

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

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

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


        return project_media;
    }

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

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

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

        await project_media.destroy({
            transaction
        });

        return project_media;
    }

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

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

        if (!project_media) {
            return project_media;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.project = await project_media.getProject({
            transaction
        });
        
        
        output.images = await project_media.getImages({
            transaction
        });
        
        
        output.videos = await project_media.getVideos({
            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.projects,
        as: 'project',
        
        where: filter.project ? {
          [Op.or]: [
            { id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
            {
              name_ar: {
                [Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

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

    ];

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

            
            if (filter.caption_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'project_media',
                        'caption_ar',
                        filter.caption_ar,
                    ),
                };
            }
            

            
            

            
            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.media_kind) {
                where = {
                    ...where,
                media_kind: filter.media_kind,
            };
            }
            
            if (filter.media_role) {
                where = {
                    ...where,
                media_role: filter.media_role,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      



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

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

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

    
};

