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

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

        const storage_buckets = await db.storage_buckets.create(
            {
                id: data.id || undefined,
        
        provider: data.provider
        ||
        null
            ,
            
        bucket_name: data.bucket_name
        ||
        null
            ,
            
        region: data.region
        ||
        null
            ,
            
        cdn_domain: data.cdn_domain
        ||
        null
            ,
            
        default_bucket: data.default_bucket
        ||
        false
        
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await storage_buckets.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        

        
        await storage_buckets.setStorage_objects(data.storage_objects || [], {
            transaction,
        });
        

        

        return storage_buckets;
    }
    

    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 storage_bucketsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                provider: item.provider
            ||
            null
            ,
            
                bucket_name: item.bucket_name
            ||
            null
            ,
            
                region: item.region
            ||
            null
            ,
            
                cdn_domain: item.cdn_domain
            ||
            null
            ,
            
                default_bucket: item.default_bucket
            ||
            false
        
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return storage_buckets;
    }

    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 storage_buckets = await db.storage_buckets.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.provider !== undefined) updatePayload.provider = data.provider;
        
        
        if (data.bucket_name !== undefined) updatePayload.bucket_name = data.bucket_name;
        
        
        if (data.region !== undefined) updatePayload.region = data.region;
        
        
        if (data.cdn_domain !== undefined) updatePayload.cdn_domain = data.cdn_domain;
        
        
        if (data.default_bucket !== undefined) updatePayload.default_bucket = data.default_bucket;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await storage_buckets.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        

        
        
        if (data.storage_objects !== undefined) {
            await storage_buckets.setStorage_objects(data.storage_objects, { transaction });
        }
        

        

        return storage_buckets;
    }

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

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

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


        return storage_buckets;
    }

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

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

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

        await storage_buckets.destroy({
            transaction
        });

        return storage_buckets;
    }

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

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

        if (!storage_buckets) {
            return storage_buckets;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        output.storage_objects_bucket = await storage_buckets.getStorage_objects_bucket({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await storage_buckets.getOrganization({
            transaction
        });
        
        
        output.storage_objects = await storage_buckets.getStorage_objects({
            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.organizations,
        as: 'organization',
        
      },


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


    ];

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

            
            if (filter.provider) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'storage_buckets',
                        'provider',
                        filter.provider,
                    ),
                };
            }
            
            if (filter.bucket_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'storage_buckets',
                        'bucket_name',
                        filter.bucket_name,
                    ),
                };
            }
            
            if (filter.region) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'storage_buckets',
                        'region',
                        filter.region,
                    ),
                };
            }
            
            if (filter.cdn_domain) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'storage_buckets',
                        'cdn_domain',
                        filter.cdn_domain,
                    ),
                };
            }
            

            
            

            

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

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


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

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


      if (filter.storage_objects) {
        const searchTerms = filter.storage_objects.split('|');

        include = [
          {
            model: db.storage_objects,
            as: 'storage_objects_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  object_key: {
                    [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,
                        },
                    };
                }
            }
        }
        

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

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

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

    
};

