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

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

        const coffee_lots = await db.coffee_lots.create(
            {
                id: data.id || undefined,
        
        lot_code: data.lot_code
        ||
        null
            ,
            
        process_type: data.process_type
        ||
        null
            ,
            
        grade: data.grade
        ||
        null
            ,
            
        crop_year: data.crop_year
        ||
        null
            ,
            
        moisture_percent: data.moisture_percent
        ||
        null
            ,
            
        tasting_notes: data.tasting_notes
        ||
        null
            ,
            
        scaa_score: data.scaa_score
        ||
        null
            ,
            
        certifications: data.certifications
        ||
        null
            ,
            
        available_quantity_kg: data.available_quantity_kg
        ||
        null
            ,
            
        is_available: data.is_available
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await coffee_lots.setRegion( data.region || null, {
            transaction,
        });
        

        

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

        return coffee_lots;
    }
    

    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 coffee_lotsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                lot_code: item.lot_code
            ||
            null
            ,
            
                process_type: item.process_type
            ||
            null
            ,
            
                grade: item.grade
            ||
            null
            ,
            
                crop_year: item.crop_year
            ||
            null
            ,
            
                moisture_percent: item.moisture_percent
            ||
            null
            ,
            
                tasting_notes: item.tasting_notes
            ||
            null
            ,
            
                scaa_score: item.scaa_score
            ||
            null
            ,
            
                certifications: item.certifications
            ||
            null
            ,
            
                available_quantity_kg: item.available_quantity_kg
            ||
            null
            ,
            
                is_available: item.is_available
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return coffee_lots;
    }

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

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


        

        const updatePayload = {};
        
        if (data.lot_code !== undefined) updatePayload.lot_code = data.lot_code;
        
        
        if (data.process_type !== undefined) updatePayload.process_type = data.process_type;
        
        
        if (data.grade !== undefined) updatePayload.grade = data.grade;
        
        
        if (data.crop_year !== undefined) updatePayload.crop_year = data.crop_year;
        
        
        if (data.moisture_percent !== undefined) updatePayload.moisture_percent = data.moisture_percent;
        
        
        if (data.tasting_notes !== undefined) updatePayload.tasting_notes = data.tasting_notes;
        
        
        if (data.scaa_score !== undefined) updatePayload.scaa_score = data.scaa_score;
        
        
        if (data.certifications !== undefined) updatePayload.certifications = data.certifications;
        
        
        if (data.available_quantity_kg !== undefined) updatePayload.available_quantity_kg = data.available_quantity_kg;
        
        
        if (data.is_available !== undefined) updatePayload.is_available = data.is_available;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.region !== undefined) {
            await coffee_lots.setRegion(
              
              data.region,
              
              { transaction }
            );
        }
        

        
        

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

        return coffee_lots;
    }

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

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

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


        return coffee_lots;
    }

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

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

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

        await coffee_lots.destroy({
            transaction
        });

        return coffee_lots;
    }

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

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

        if (!coffee_lots) {
            return coffee_lots;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.inquiries_requested_lot = await coffee_lots.getInquiries_requested_lot({
            transaction
        });
        
        
        
        
        
        output.region = await coffee_lots.getRegion({
            transaction
        });
        
        
        output.images = await coffee_lots.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.coffee_regions,
        as: 'region',
        
        where: filter.region ? {
          [Op.or]: [
            { id: { [Op.in]: filter.region.split('|').map(term => Utils.uuid(term)) } },
            {
              region_name: {
                [Op.or]: filter.region.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.lot_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'coffee_lots',
                        'lot_code',
                        filter.lot_code,
                    ),
                };
            }
            
            if (filter.tasting_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'coffee_lots',
                        'tasting_notes',
                        filter.tasting_notes,
                    ),
                };
            }
            
            if (filter.certifications) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'coffee_lots',
                        'certifications',
                        filter.certifications,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.process_type) {
                where = {
                    ...where,
                process_type: filter.process_type,
            };
            }
            
            if (filter.grade) {
                where = {
                    ...where,
                grade: filter.grade,
            };
            }
            
            if (filter.is_available) {
                where = {
                    ...where,
                is_available: filter.is_available,
            };
            }
            


      



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

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

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

    
};

