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

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

        const gig_levels = await db.gig_levels.create(
            {
                id: data.id || undefined,
        
        level_number: data.level_number
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        deliverables_json: data.deliverables_json
        ||
        null
            ,
            
        price: data.price
        ||
        null
            ,
            
        duration_minutes: data.duration_minutes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await gig_levels.setGig( data.gig || null, {
            transaction,
        });
        

        

        

        return gig_levels;
    }
    

    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 gig_levelsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                level_number: item.level_number
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                deliverables_json: item.deliverables_json
            ||
            null
            ,
            
                price: item.price
            ||
            null
            ,
            
                duration_minutes: item.duration_minutes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return gig_levels;
    }

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

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


        

        const updatePayload = {};
        
        if (data.level_number !== undefined) updatePayload.level_number = data.level_number;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.deliverables_json !== undefined) updatePayload.deliverables_json = data.deliverables_json;
        
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        if (data.duration_minutes !== undefined) updatePayload.duration_minutes = data.duration_minutes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.gig !== undefined) {
            await gig_levels.setGig(
              
              data.gig,
              
              { transaction }
            );
        }
        

        
        

        

        return gig_levels;
    }

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

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

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


        return gig_levels;
    }

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

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

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

        await gig_levels.destroy({
            transaction
        });

        return gig_levels;
    }

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

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

        if (!gig_levels) {
            return gig_levels;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.bookings_gig_level = await gig_levels.getBookings_gig_level({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.gig = await gig_levels.getGig({
            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.gigs,
        as: 'gig',
        
        where: filter.gig ? {
          [Op.or]: [
            { id: { [Op.in]: filter.gig.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.gig.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

            


      



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

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

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

    
};

