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

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

        const blog_posts = await db.blog_posts.create(
            {
                id: data.id || undefined,
        
        title_ar: data.title_ar
        ||
        null
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        excerpt_ar: data.excerpt_ar
        ||
        null
            ,
            
        content_ar: data.content_ar
        ||
        null
            ,
            
        publish_status: data.publish_status
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
        is_featured: data.is_featured
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await blog_posts.setCategory( data.category || null, {
            transaction,
        });
        
        await blog_posts.setAuthor( data.author || null, {
            transaction,
        });
        

        
        await blog_posts.setRelated_stones(data.related_stones || [], {
            transaction,
        });
        
        await blog_posts.setRelated_projects(data.related_projects || [], {
            transaction,
        });
        

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

        return blog_posts;
    }
    

    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 blog_postsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title_ar: item.title_ar
            ||
            null
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                excerpt_ar: item.excerpt_ar
            ||
            null
            ,
            
                content_ar: item.content_ar
            ||
            null
            ,
            
                publish_status: item.publish_status
            ||
            null
            ,
            
                published_at: item.published_at
            ||
            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 blog_posts = await db.blog_posts.bulkCreate(blog_postsData, { transaction });

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

        return blog_posts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title_ar !== undefined) updatePayload.title_ar = data.title_ar;
        
        
        if (data.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.excerpt_ar !== undefined) updatePayload.excerpt_ar = data.excerpt_ar;
        
        
        if (data.content_ar !== undefined) updatePayload.content_ar = data.content_ar;
        
        
        if (data.publish_status !== undefined) updatePayload.publish_status = data.publish_status;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        if (data.is_featured !== undefined) updatePayload.is_featured = data.is_featured;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.category !== undefined) {
            await blog_posts.setCategory(
              
              data.category,
              
              { transaction }
            );
        }
        
        if (data.author !== undefined) {
            await blog_posts.setAuthor(
              
              data.author,
              
              { transaction }
            );
        }
        

        
        
        if (data.related_stones !== undefined) {
            await blog_posts.setRelated_stones(data.related_stones, { transaction });
        }
        
        if (data.related_projects !== undefined) {
            await blog_posts.setRelated_projects(data.related_projects, { transaction });
        }
        

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

        return blog_posts;
    }

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

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

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


        return blog_posts;
    }

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

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

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

        await blog_posts.destroy({
            transaction
        });

        return blog_posts;
    }

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

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

        if (!blog_posts) {
            return blog_posts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.category = await blog_posts.getCategory({
            transaction
        });
        
        
        output.author = await blog_posts.getAuthor({
            transaction
        });
        
        
        output.featured_image = await blog_posts.getFeatured_image({
            transaction
        });
        
        
        output.attachments = await blog_posts.getAttachments({
            transaction
        });
        
        
        output.related_stones = await blog_posts.getRelated_stones({
            transaction
        });
        
        
        output.related_projects = await blog_posts.getRelated_projects({
            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.blog_categories,
        as: 'category',
        
        where: filter.category ? {
          [Op.or]: [
            { id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
            {
              name_ar: {
                [Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.stones,
        as: 'related_stones',
        required: false,
      },

      {
        model: db.projects,
        as: 'related_projects',
        required: false,
      },


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

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

    ];

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

            
            if (filter.title_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'blog_posts',
                        'title_ar',
                        filter.title_ar,
                    ),
                };
            }
            
            if (filter.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'blog_posts',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.excerpt_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'blog_posts',
                        'excerpt_ar',
                        filter.excerpt_ar,
                    ),
                };
            }
            
            if (filter.content_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'blog_posts',
                        'content_ar',
                        filter.content_ar,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      


      if (filter.related_stones) {
        const searchTerms = filter.related_stones.split('|');

        include = [
          {
            model: db.stones,
            as: 'related_stones_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name_ar: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.related_projects) {
        const searchTerms = filter.related_projects.split('|');

        include = [
          {
            model: db.projects,
            as: 'related_projects_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name_ar: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

    
};

