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

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

        const gigs = await db.gigs.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        impressions: data.impressions
        ||
        null
            ,
            
        total_orders: data.total_orders
        ||
        null
            ,
            
        rating: data.rating
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await gigs.setTutor_profile( data.tutor_profile || null, {
            transaction,
        });
        
        await gigs.setCategory( data.category || null, {
            transaction,
        });
        

        
        await gigs.setTags(data.tags || [], {
            transaction,
        });
        

        

        return gigs;
    }
    

    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 gigsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                impressions: item.impressions
            ||
            null
            ,
            
                total_orders: item.total_orders
            ||
            null
            ,
            
                rating: item.rating
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return gigs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.impressions !== undefined) updatePayload.impressions = data.impressions;
        
        
        if (data.total_orders !== undefined) updatePayload.total_orders = data.total_orders;
        
        
        if (data.rating !== undefined) updatePayload.rating = data.rating;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tutor_profile !== undefined) {
            await gigs.setTutor_profile(
              
              data.tutor_profile,
              
              { transaction }
            );
        }
        
        if (data.category !== undefined) {
            await gigs.setCategory(
              
              data.category,
              
              { transaction }
            );
        }
        

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

        

        return gigs;
    }

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

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

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


        return gigs;
    }

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

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

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

        await gigs.destroy({
            transaction
        });

        return gigs;
    }

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

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

        if (!gigs) {
            return gigs;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.gig_levels_gig = await gigs.getGig_levels_gig({
            transaction
        });
        
        
        
        output.bookings_gig = await gigs.getBookings_gig({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.invites_gig = await gigs.getInvites_gig({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tutor_profile = await gigs.getTutor_profile({
            transaction
        });
        
        
        output.category = await gigs.getCategory({
            transaction
        });
        
        
        output.tags = await gigs.getTags({
            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.tutor_profiles,
        as: 'tutor_profile',
        
        where: filter.tutor_profile ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tutor_profile.split('|').map(term => Utils.uuid(term)) } },
            {
              headline: {
                [Op.or]: filter.tutor_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


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


    ];

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

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

            
            

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

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

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

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

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

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

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

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

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


      

      


      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)) } },
                { 
                  label: {
                    [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.gigs.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(
                        'gigs',
                        'title',
                        query,
                    ),
                ],
            };
        }

        const records = await db.gigs.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,
        }));
    }

    
};

