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

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

        const bookings = await db.bookings.create(
            {
                id: data.id || undefined,
        
        level_number: data.level_number
        ||
        null
            ,
            
        level_name: data.level_name
        ||
        null
            ,
            
        price: data.price
        ||
        null
            ,
            
        platform_fee: data.platform_fee
        ||
        null
            ,
            
        tutor_payout: data.tutor_payout
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        escrow_status: data.escrow_status
        ||
        null
            ,
            
        scheduled_at: data.scheduled_at
        ||
        null
            ,
            
        accepted_at: data.accepted_at
        ||
        null
            ,
            
        milestone_submitted_at: data.milestone_submitted_at
        ||
        null
            ,
            
        auto_release_at: data.auto_release_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        deliverable_notes: data.deliverable_notes
        ||
        null
            ,
            
        revision_count: data.revision_count
        ||
        null
            ,
            
        revision_reason: data.revision_reason
        ||
        null
            ,
            
        jitsi_meet_meeting_id: data.jitsi_meet_meeting_id
        ||
        null
            ,
            
        jitsi_meet_password: data.jitsi_meet_password
        ||
        null
            ,
            
        admin_note: data.admin_note
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await bookings.setLearner( data.learner || null, {
            transaction,
        });
        
        await bookings.setTutor( data.tutor || null, {
            transaction,
        });
        
        await bookings.setGig( data.gig || null, {
            transaction,
        });
        
        await bookings.setGig_level( data.gig_level || null, {
            transaction,
        });
        

        

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

        return bookings;
    }
    

    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 bookingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                level_number: item.level_number
            ||
            null
            ,
            
                level_name: item.level_name
            ||
            null
            ,
            
                price: item.price
            ||
            null
            ,
            
                platform_fee: item.platform_fee
            ||
            null
            ,
            
                tutor_payout: item.tutor_payout
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                escrow_status: item.escrow_status
            ||
            null
            ,
            
                scheduled_at: item.scheduled_at
            ||
            null
            ,
            
                accepted_at: item.accepted_at
            ||
            null
            ,
            
                milestone_submitted_at: item.milestone_submitted_at
            ||
            null
            ,
            
                auto_release_at: item.auto_release_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
                deliverable_notes: item.deliverable_notes
            ||
            null
            ,
            
                revision_count: item.revision_count
            ||
            null
            ,
            
                revision_reason: item.revision_reason
            ||
            null
            ,
            
                jitsi_meet_meeting_id: item.jitsi_meet_meeting_id
            ||
            null
            ,
            
                jitsi_meet_password: item.jitsi_meet_password
            ||
            null
            ,
            
                admin_note: item.admin_note
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return bookings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.level_number !== undefined) updatePayload.level_number = data.level_number;
        
        
        if (data.level_name !== undefined) updatePayload.level_name = data.level_name;
        
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        if (data.platform_fee !== undefined) updatePayload.platform_fee = data.platform_fee;
        
        
        if (data.tutor_payout !== undefined) updatePayload.tutor_payout = data.tutor_payout;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.escrow_status !== undefined) updatePayload.escrow_status = data.escrow_status;
        
        
        if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
        
        
        if (data.accepted_at !== undefined) updatePayload.accepted_at = data.accepted_at;
        
        
        if (data.milestone_submitted_at !== undefined) updatePayload.milestone_submitted_at = data.milestone_submitted_at;
        
        
        if (data.auto_release_at !== undefined) updatePayload.auto_release_at = data.auto_release_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.deliverable_notes !== undefined) updatePayload.deliverable_notes = data.deliverable_notes;
        
        
        if (data.revision_count !== undefined) updatePayload.revision_count = data.revision_count;
        
        
        if (data.revision_reason !== undefined) updatePayload.revision_reason = data.revision_reason;
        
        
        if (data.jitsi_meet_meeting_id !== undefined) updatePayload.jitsi_meet_meeting_id = data.jitsi_meet_meeting_id;
        
        
        if (data.jitsi_meet_password !== undefined) updatePayload.jitsi_meet_password = data.jitsi_meet_password;
        
        
        if (data.admin_note !== undefined) updatePayload.admin_note = data.admin_note;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.learner !== undefined) {
            await bookings.setLearner(
              
              data.learner,
              
              { transaction }
            );
        }
        
        if (data.tutor !== undefined) {
            await bookings.setTutor(
              
              data.tutor,
              
              { transaction }
            );
        }
        
        if (data.gig !== undefined) {
            await bookings.setGig(
              
              data.gig,
              
              { transaction }
            );
        }
        
        if (data.gig_level !== undefined) {
            await bookings.setGig_level(
              
              data.gig_level,
              
              { transaction }
            );
        }
        

        
        

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

        return bookings;
    }

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

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

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


        return bookings;
    }

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

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

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

        await bookings.destroy({
            transaction
        });

        return bookings;
    }

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

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

        if (!bookings) {
            return bookings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.reviews_booking = await bookings.getReviews_booking({
            transaction
        });
        
        
        output.notes_booking = await bookings.getNotes_booking({
            transaction
        });
        
        
        output.disputes_booking = await bookings.getDisputes_booking({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.certificates_booking = await bookings.getCertificates_booking({
            transaction
        });
        
        
        
        output.learner = await bookings.getLearner({
            transaction
        });
        
        
        output.tutor = await bookings.getTutor({
            transaction
        });
        
        
        output.gig = await bookings.getGig({
            transaction
        });
        
        
        output.gig_level = await bookings.getGig_level({
            transaction
        });
        
        
        output.deliverable_files = await bookings.getDeliverable_files({
            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: 'learner',
        
        where: filter.learner ? {
          [Op.or]: [
            { id: { [Op.in]: filter.learner.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.learner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        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}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.level_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bookings',
                        'level_name',
                        filter.level_name,
                    ),
                };
            }
            
            if (filter.deliverable_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bookings',
                        'deliverable_notes',
                        filter.deliverable_notes,
                    ),
                };
            }
            
            if (filter.revision_reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bookings',
                        'revision_reason',
                        filter.revision_reason,
                    ),
                };
            }
            
            if (filter.jitsi_meet_meeting_id) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bookings',
                        'jitsi_meet_meeting_id',
                        filter.jitsi_meet_meeting_id,
                    ),
                };
            }
            
            if (filter.jitsi_meet_password) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bookings',
                        'jitsi_meet_password',
                        filter.jitsi_meet_password,
                    ),
                };
            }
            
            if (filter.admin_note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bookings',
                        'admin_note',
                        filter.admin_note,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    revision_count: {
                    ...where.revision_count,
                            [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.escrow_status) {
                where = {
                    ...where,
                escrow_status: filter.escrow_status,
            };
            }
            


      

      

      

      



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

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

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

    
};

