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

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

        const marketplace_listings = await db.marketplace_listings.create(
            {
                id: data.id || undefined,
        
        listing_title: data.listing_title
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        product_form: data.product_form
        ||
        null
            ,
            
        available_quantity_kg: data.available_quantity_kg
        ||
        null
            ,
            
        price_per_kg: data.price_per_kg
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        available_from: data.available_from
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        listing_status: data.listing_status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await marketplace_listings.setSeller_tenant( data.seller_tenant || null, {
            transaction,
        });
        
        await marketplace_listings.setHarvest( data.harvest || null, {
            transaction,
        });
        
        await marketplace_listings.setSpecies( data.species || null, {
            transaction,
        });
        
        await marketplace_listings.setFulfillment_location( data.fulfillment_location || null, {
            transaction,
        });
        
        await marketplace_listings.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return marketplace_listings;
    }
    

    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 marketplace_listingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                listing_title: item.listing_title
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                product_form: item.product_form
            ||
            null
            ,
            
                available_quantity_kg: item.available_quantity_kg
            ||
            null
            ,
            
                price_per_kg: item.price_per_kg
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                available_from: item.available_from
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                listing_status: item.listing_status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return marketplace_listings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.listing_title !== undefined) updatePayload.listing_title = data.listing_title;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.product_form !== undefined) updatePayload.product_form = data.product_form;
        
        
        if (data.available_quantity_kg !== undefined) updatePayload.available_quantity_kg = data.available_quantity_kg;
        
        
        if (data.price_per_kg !== undefined) updatePayload.price_per_kg = data.price_per_kg;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.available_from !== undefined) updatePayload.available_from = data.available_from;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.listing_status !== undefined) updatePayload.listing_status = data.listing_status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.seller_tenant !== undefined) {
            await marketplace_listings.setSeller_tenant(
              
              data.seller_tenant,
              
              { transaction }
            );
        }
        
        if (data.harvest !== undefined) {
            await marketplace_listings.setHarvest(
              
              data.harvest,
              
              { transaction }
            );
        }
        
        if (data.species !== undefined) {
            await marketplace_listings.setSpecies(
              
              data.species,
              
              { transaction }
            );
        }
        
        if (data.fulfillment_location !== undefined) {
            await marketplace_listings.setFulfillment_location(
              
              data.fulfillment_location,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await marketplace_listings.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return marketplace_listings;
    }

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

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

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


        return marketplace_listings;
    }

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

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

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

        await marketplace_listings.destroy({
            transaction
        });

        return marketplace_listings;
    }

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

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

        if (!marketplace_listings) {
            return marketplace_listings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.order_items_listing = await marketplace_listings.getOrder_items_listing({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.seller_tenant = await marketplace_listings.getSeller_tenant({
            transaction
        });
        
        
        output.harvest = await marketplace_listings.getHarvest({
            transaction
        });
        
        
        output.species = await marketplace_listings.getSpecies({
            transaction
        });
        
        
        output.photos = await marketplace_listings.getPhotos({
            transaction
        });
        
        
        output.fulfillment_location = await marketplace_listings.getFulfillment_location({
            transaction
        });
        
        
        output.organizations = await marketplace_listings.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



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

    ];

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

            
            if (filter.listing_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'marketplace_listings',
                        'listing_title',
                        filter.listing_title,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'marketplace_listings',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'marketplace_listings',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            

            
            

            
            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.price_per_kgRange) {
                const [start, end] = filter.price_per_kgRange;

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

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

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

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

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

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

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

            
            if (filter.product_form) {
                where = {
                    ...where,
                product_form: filter.product_form,
            };
            }
            
            if (filter.listing_status) {
                where = {
                    ...where,
                listing_status: filter.listing_status,
            };
            }
            


      

      

      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.marketplace_listings.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'marketplace_listings',
                        'listing_title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

