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

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

        const tickets = await db.tickets.create(
            {
                id: data.id || undefined,
        
        ticket_code: data.ticket_code
        ||
        null
            ,
            
        price_amount: data.price_amount
        ||
        null
            ,
            
        currency_code: data.currency_code
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        purchased_at: data.purchased_at
        ||
        null
            ,
            
        checked_in_at: data.checked_in_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await tickets.setEvent( data.event || null, {
            transaction,
        });
        
        await tickets.setBuyer( data.buyer || null, {
            transaction,
        });
        

        

        

        return tickets;
    }
    

    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 ticketsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                ticket_code: item.ticket_code
            ||
            null
            ,
            
                price_amount: item.price_amount
            ||
            null
            ,
            
                currency_code: item.currency_code
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                purchased_at: item.purchased_at
            ||
            null
            ,
            
                checked_in_at: item.checked_in_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return tickets;
    }

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

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


        

        const updatePayload = {};
        
        if (data.ticket_code !== undefined) updatePayload.ticket_code = data.ticket_code;
        
        
        if (data.price_amount !== undefined) updatePayload.price_amount = data.price_amount;
        
        
        if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.purchased_at !== undefined) updatePayload.purchased_at = data.purchased_at;
        
        
        if (data.checked_in_at !== undefined) updatePayload.checked_in_at = data.checked_in_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.event !== undefined) {
            await tickets.setEvent(
              
              data.event,
              
              { transaction }
            );
        }
        
        if (data.buyer !== undefined) {
            await tickets.setBuyer(
              
              data.buyer,
              
              { transaction }
            );
        }
        

        
        

        

        return tickets;
    }

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

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

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


        return tickets;
    }

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

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

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

        await tickets.destroy({
            transaction
        });

        return tickets;
    }

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

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

        if (!tickets) {
            return tickets;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.transactions_ticket = await tickets.getTransactions_ticket({
            transaction
        });
        
        
        
        
        
        
        
        output.event = await tickets.getEvent({
            transaction
        });
        
        
        output.buyer = await tickets.getBuyer({
            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.events,
        as: 'event',
        
        where: filter.event ? {
          [Op.or]: [
            { id: { [Op.in]: filter.event.split('|').map(term => Utils.uuid(term)) } },
            {
              title_text: {
                [Op.or]: filter.event.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.ticket_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'tickets',
                        'ticket_code',
                        filter.ticket_code,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.currency_code) {
                where = {
                    ...where,
                currency_code: filter.currency_code,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.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.tickets.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(
                        'tickets',
                        'ticket_code',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

