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

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

        const stones = await db.stones.create(
            {
                id: data.id || undefined,
        
        name_ar: data.name_ar
        ||
        null
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        short_description_ar: data.short_description_ar
        ||
        null
            ,
            
        description_ar: data.description_ar
        ||
        null
            ,
            
        density: data.density
        ||
        null
            ,
            
        water_absorption: data.water_absorption
        ||
        null
            ,
            
        compressive_strength: data.compressive_strength
        ||
        null
            ,
            
        flexural_strength: data.flexural_strength
        ||
        null
            ,
            
        origin_type: data.origin_type
        ||
        null
            ,
            
        origin_country: data.origin_country
        ||
        null
            ,
            
        is_featured: data.is_featured
        ||
        false
        
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await stones.setCategory( data.category || null, {
            transaction,
        });
        
        await stones.setColor( data.color || null, {
            transaction,
        });
        

        
        await stones.setFinishes(data.finishes || [], {
            transaction,
        });
        
        await stones.setApplications(data.applications || [], {
            transaction,
        });
        

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

        return stones;
    }
    

    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 stonesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name_ar: item.name_ar
            ||
            null
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                short_description_ar: item.short_description_ar
            ||
            null
            ,
            
                description_ar: item.description_ar
            ||
            null
            ,
            
                density: item.density
            ||
            null
            ,
            
                water_absorption: item.water_absorption
            ||
            null
            ,
            
                compressive_strength: item.compressive_strength
            ||
            null
            ,
            
                flexural_strength: item.flexural_strength
            ||
            null
            ,
            
                origin_type: item.origin_type
            ||
            null
            ,
            
                origin_country: item.origin_country
            ||
            null
            ,
            
                is_featured: item.is_featured
            ||
            false
        
            ,
            
                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 stones = await db.stones.bulkCreate(stonesData, { transaction });

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

        return stones;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name_ar !== undefined) updatePayload.name_ar = data.name_ar;
        
        
        if (data.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.short_description_ar !== undefined) updatePayload.short_description_ar = data.short_description_ar;
        
        
        if (data.description_ar !== undefined) updatePayload.description_ar = data.description_ar;
        
        
        if (data.density !== undefined) updatePayload.density = data.density;
        
        
        if (data.water_absorption !== undefined) updatePayload.water_absorption = data.water_absorption;
        
        
        if (data.compressive_strength !== undefined) updatePayload.compressive_strength = data.compressive_strength;
        
        
        if (data.flexural_strength !== undefined) updatePayload.flexural_strength = data.flexural_strength;
        
        
        if (data.origin_type !== undefined) updatePayload.origin_type = data.origin_type;
        
        
        if (data.origin_country !== undefined) updatePayload.origin_country = data.origin_country;
        
        
        if (data.is_featured !== undefined) updatePayload.is_featured = data.is_featured;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.category !== undefined) {
            await stones.setCategory(
              
              data.category,
              
              { transaction }
            );
        }
        
        if (data.color !== undefined) {
            await stones.setColor(
              
              data.color,
              
              { transaction }
            );
        }
        

        
        
        if (data.finishes !== undefined) {
            await stones.setFinishes(data.finishes, { transaction });
        }
        
        if (data.applications !== undefined) {
            await stones.setApplications(data.applications, { transaction });
        }
        

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

        return stones;
    }

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

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

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


        return stones;
    }

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

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

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

        await stones.destroy({
            transaction
        });

        return stones;
    }

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

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

        if (!stones) {
            return stones;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.stone_variants_stone = await stones.getStone_variants_stone({
            transaction
        });
        
        
        output.stone_3d_assets_stone = await stones.getStone_3d_assets_stone({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.lead_requests_interested_stone = await stones.getLead_requests_interested_stone({
            transaction
        });
        
        
        
        
        
        
        
        output.category = await stones.getCategory({
            transaction
        });
        
        
        output.color = await stones.getColor({
            transaction
        });
        
        
        output.finishes = await stones.getFinishes({
            transaction
        });
        
        
        output.applications = await stones.getApplications({
            transaction
        });
        
        
        output.gallery_images = await stones.getGallery_images({
            transaction
        });
        
        
        output.technical_sheet_files = await stones.getTechnical_sheet_files({
            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.stone_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.stone_colors,
        as: 'color',
        
        where: filter.color ? {
          [Op.or]: [
            { id: { [Op.in]: filter.color.split('|').map(term => Utils.uuid(term)) } },
            {
              name_ar: {
                [Op.or]: filter.color.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },


      {
        model: db.finishes,
        as: 'finishes',
        required: false,
      },

      {
        model: db.applications,
        as: 'applications',
        required: false,
      },


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

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

    ];

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

            
            if (filter.name_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stones',
                        'name_ar',
                        filter.name_ar,
                    ),
                };
            }
            
            if (filter.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stones',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.short_description_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stones',
                        'short_description_ar',
                        filter.short_description_ar,
                    ),
                };
            }
            
            if (filter.description_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stones',
                        'description_ar',
                        filter.description_ar,
                    ),
                };
            }
            
            if (filter.origin_country) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stones',
                        'origin_country',
                        filter.origin_country,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    density: {
                    ...where.density,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.water_absorptionRange) {
                const [start, end] = filter.water_absorptionRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    water_absorption: {
                    ...where.water_absorption,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.compressive_strengthRange) {
                const [start, end] = filter.compressive_strengthRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    compressive_strength: {
                    ...where.compressive_strength,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.flexural_strengthRange) {
                const [start, end] = filter.flexural_strengthRange;

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

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

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

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


      

      


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

        include = [
          {
            model: db.finishes,
            as: 'finishes_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.applications) {
        const searchTerms = filter.applications.split('|');

        include = [
          {
            model: db.applications,
            as: 'applications_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.stones.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(
                        'stones',
                        'name_ar',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

