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

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

        const ota_connections = await db.ota_connections.create(
            {
                id: data.id || undefined,
        
        provider: data.provider
        ||
        null
            ,
            
        account_identifier: data.account_identifier
        ||
        null
            ,
            
        api_key_reference: data.api_key_reference
        ||
        null
            ,
            
        inventory_sync_enabled: data.inventory_sync_enabled
        ||
        false
        
            ,
            
        rate_sync_enabled: data.rate_sync_enabled
        ||
        false
        
            ,
            
        last_sync_at: data.last_sync_at
        ||
        null
            ,
            
        sync_status: data.sync_status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ota_connections.setHotel( data.hotel || null, {
            transaction,
        });
        
        await ota_connections.setSales_channel( data.sales_channel || null, {
            transaction,
        });
        
        await ota_connections.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return ota_connections;
    }
    

    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 ota_connectionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                provider: item.provider
            ||
            null
            ,
            
                account_identifier: item.account_identifier
            ||
            null
            ,
            
                api_key_reference: item.api_key_reference
            ||
            null
            ,
            
                inventory_sync_enabled: item.inventory_sync_enabled
            ||
            false
        
            ,
            
                rate_sync_enabled: item.rate_sync_enabled
            ||
            false
        
            ,
            
                last_sync_at: item.last_sync_at
            ||
            null
            ,
            
                sync_status: item.sync_status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ota_connections;
    }

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

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


        

        const updatePayload = {};
        
        if (data.provider !== undefined) updatePayload.provider = data.provider;
        
        
        if (data.account_identifier !== undefined) updatePayload.account_identifier = data.account_identifier;
        
        
        if (data.api_key_reference !== undefined) updatePayload.api_key_reference = data.api_key_reference;
        
        
        if (data.inventory_sync_enabled !== undefined) updatePayload.inventory_sync_enabled = data.inventory_sync_enabled;
        
        
        if (data.rate_sync_enabled !== undefined) updatePayload.rate_sync_enabled = data.rate_sync_enabled;
        
        
        if (data.last_sync_at !== undefined) updatePayload.last_sync_at = data.last_sync_at;
        
        
        if (data.sync_status !== undefined) updatePayload.sync_status = data.sync_status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.hotel !== undefined) {
            await ota_connections.setHotel(
              
              data.hotel,
              
              { transaction }
            );
        }
        
        if (data.sales_channel !== undefined) {
            await ota_connections.setSales_channel(
              
              data.sales_channel,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await ota_connections.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return ota_connections;
    }

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

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

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


        return ota_connections;
    }

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

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

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

        await ota_connections.destroy({
            transaction
        });

        return ota_connections;
    }

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

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

        if (!ota_connections) {
            return ota_connections;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.hotel = await ota_connections.getHotel({
            transaction
        });
        
        
        output.sales_channel = await ota_connections.getSales_channel({
            transaction
        });
        
        
        output.organizations = await ota_connections.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.account_identifier) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ota_connections',
                        'account_identifier',
                        filter.account_identifier,
                    ),
                };
            }
            
            if (filter.api_key_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ota_connections',
                        'api_key_reference',
                        filter.api_key_reference,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.provider) {
                where = {
                    ...where,
                provider: filter.provider,
            };
            }
            
            if (filter.inventory_sync_enabled) {
                where = {
                    ...where,
                inventory_sync_enabled: filter.inventory_sync_enabled,
            };
            }
            
            if (filter.rate_sync_enabled) {
                where = {
                    ...where,
                rate_sync_enabled: filter.rate_sync_enabled,
            };
            }
            
            if (filter.sync_status) {
                where = {
                    ...where,
                sync_status: filter.sync_status,
            };
            }
            


      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.ota_connections.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

