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

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

        const stone_variants = await db.stone_variants.create(
            {
                id: data.id || undefined,
        
        variant_type: data.variant_type
        ||
        null
            ,
            
        sku: data.sku
        ||
        null
            ,
            
        length_mm: data.length_mm
        ||
        null
            ,
            
        width_mm: data.width_mm
        ||
        null
            ,
            
        thickness_mm: data.thickness_mm
        ||
        null
            ,
            
        weight_kg: data.weight_kg
        ||
        null
            ,
            
        availability_status: data.availability_status
        ||
        null
            ,
            
        base_price: data.base_price
        ||
        null
            ,
            
        price_note_ar: data.price_note_ar
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await stone_variants.setStone( data.stone || null, {
            transaction,
        });
        

        

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

        return stone_variants;
    }
    

    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 stone_variantsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                variant_type: item.variant_type
            ||
            null
            ,
            
                sku: item.sku
            ||
            null
            ,
            
                length_mm: item.length_mm
            ||
            null
            ,
            
                width_mm: item.width_mm
            ||
            null
            ,
            
                thickness_mm: item.thickness_mm
            ||
            null
            ,
            
                weight_kg: item.weight_kg
            ||
            null
            ,
            
                availability_status: item.availability_status
            ||
            null
            ,
            
                base_price: item.base_price
            ||
            null
            ,
            
                price_note_ar: item.price_note_ar
            ||
            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 stone_variants = await db.stone_variants.bulkCreate(stone_variantsData, { transaction });

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

        return stone_variants;
    }

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

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


        

        const updatePayload = {};
        
        if (data.variant_type !== undefined) updatePayload.variant_type = data.variant_type;
        
        
        if (data.sku !== undefined) updatePayload.sku = data.sku;
        
        
        if (data.length_mm !== undefined) updatePayload.length_mm = data.length_mm;
        
        
        if (data.width_mm !== undefined) updatePayload.width_mm = data.width_mm;
        
        
        if (data.thickness_mm !== undefined) updatePayload.thickness_mm = data.thickness_mm;
        
        
        if (data.weight_kg !== undefined) updatePayload.weight_kg = data.weight_kg;
        
        
        if (data.availability_status !== undefined) updatePayload.availability_status = data.availability_status;
        
        
        if (data.base_price !== undefined) updatePayload.base_price = data.base_price;
        
        
        if (data.price_note_ar !== undefined) updatePayload.price_note_ar = data.price_note_ar;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.stone !== undefined) {
            await stone_variants.setStone(
              
              data.stone,
              
              { transaction }
            );
        }
        

        
        

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

        return stone_variants;
    }

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

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

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


        return stone_variants;
    }

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

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

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

        await stone_variants.destroy({
            transaction
        });

        return stone_variants;
    }

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

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

        if (!stone_variants) {
            return stone_variants;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.quote_items_stone_variant = await stone_variants.getQuote_items_stone_variant({
            transaction
        });
        
        
        
        
        
        
        output.stone = await stone_variants.getStone({
            transaction
        });
        
        
        output.images = await stone_variants.getImages({
            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.stones,
        as: 'stone',
        
        where: filter.stone ? {
          [Op.or]: [
            { id: { [Op.in]: filter.stone.split('|').map(term => Utils.uuid(term)) } },
            {
              name_ar: {
                [Op.or]: filter.stone.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.sku) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stone_variants',
                        'sku',
                        filter.sku,
                    ),
                };
            }
            
            if (filter.price_note_ar) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stone_variants',
                        'price_note_ar',
                        filter.price_note_ar,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.variant_type) {
                where = {
                    ...where,
                variant_type: filter.variant_type,
            };
            }
            
            if (filter.availability_status) {
                where = {
                    ...where,
                availability_status: filter.availability_status,
            };
            }
            
            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.stone_variants.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(
                        'stone_variants',
                        'sku',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

