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

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

        const service_listings = await db.service_listings.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        pricing_model: data.pricing_model
        ||
        null
            ,
            
        starting_price: data.starting_price
        ||
        null
            ,
            
        delivery_days: data.delivery_days
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        is_featured: data.is_featured
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await service_listings.setFreelancer( data.freelancer || null, {
            transaction,
        });
        
        await service_listings.setCategory( data.category || null, {
            transaction,
        });
        

        
        await service_listings.setTags(data.tags || [], {
            transaction,
        });
        
        await service_listings.setIncluded_skills(data.included_skills || [], {
            transaction,
        });
        

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

        return service_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 service_listingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                pricing_model: item.pricing_model
            ||
            null
            ,
            
                starting_price: item.starting_price
            ||
            null
            ,
            
                delivery_days: item.delivery_days
            ||
            null
            ,
            
                status: item.status
            ||
            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 service_listings = await db.service_listings.bulkCreate(service_listingsData, { transaction });

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

        return service_listings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.pricing_model !== undefined) updatePayload.pricing_model = data.pricing_model;
        
        
        if (data.starting_price !== undefined) updatePayload.starting_price = data.starting_price;
        
        
        if (data.delivery_days !== undefined) updatePayload.delivery_days = data.delivery_days;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.is_featured !== undefined) updatePayload.is_featured = data.is_featured;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.freelancer !== undefined) {
            await service_listings.setFreelancer(
              
              data.freelancer,
              
              { transaction }
            );
        }
        
        if (data.category !== undefined) {
            await service_listings.setCategory(
              
              data.category,
              
              { transaction }
            );
        }
        

        
        
        if (data.tags !== undefined) {
            await service_listings.setTags(data.tags, { transaction });
        }
        
        if (data.included_skills !== undefined) {
            await service_listings.setIncluded_skills(data.included_skills, { transaction });
        }
        

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

        return service_listings;
    }

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

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

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


        return service_listings;
    }

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

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

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

        await service_listings.destroy({
            transaction
        });

        return service_listings;
    }

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

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

        if (!service_listings) {
            return service_listings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.freelancer = await service_listings.getFreelancer({
            transaction
        });
        
        
        output.category = await service_listings.getCategory({
            transaction
        });
        
        
        output.gallery_images = await service_listings.getGallery_images({
            transaction
        });
        
        
        output.sample_files = await service_listings.getSample_files({
            transaction
        });
        
        
        output.tags = await service_listings.getTags({
            transaction
        });
        
        
        output.included_skills = await service_listings.getIncluded_skills({
            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.users,
        as: 'freelancer',
        
        where: filter.freelancer ? {
          [Op.or]: [
            { id: { [Op.in]: filter.freelancer.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.freelancer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


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

      {
        model: db.skills,
        as: 'included_skills',
        required: false,
      },


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

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

    ];

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

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

            
            

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

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

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

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

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

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

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


      

      


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

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

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

        include = [
          {
            model: db.skills,
            as: 'included_skills_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [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.service_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, ) {
        let where = {};
        
        

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

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

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

    
};

