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

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

        const code_repositories = await db.code_repositories.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        repo_type: data.repo_type
        ||
        null
            ,
            
        remote_url: data.remote_url
        ||
        null
            ,
            
        default_branch: data.default_branch
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        last_sync_at: data.last_sync_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await code_repositories.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await code_repositories.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await code_repositories.setFiles(data.files || [], {
            transaction,
        });
        

        

        return code_repositories;
    }
    

    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 code_repositoriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                repo_type: item.repo_type
            ||
            null
            ,
            
                remote_url: item.remote_url
            ||
            null
            ,
            
                default_branch: item.default_branch
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                last_sync_at: item.last_sync_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return code_repositories;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.repo_type !== undefined) updatePayload.repo_type = data.repo_type;
        
        
        if (data.remote_url !== undefined) updatePayload.remote_url = data.remote_url;
        
        
        if (data.default_branch !== undefined) updatePayload.default_branch = data.default_branch;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.last_sync_at !== undefined) updatePayload.last_sync_at = data.last_sync_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workspace !== undefined) {
            await code_repositories.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await code_repositories.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.files !== undefined) {
            await code_repositories.setFiles(data.files, { transaction });
        }
        

        

        return code_repositories;
    }

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

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

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


        return code_repositories;
    }

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

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

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

        await code_repositories.destroy({
            transaction
        });

        return code_repositories;
    }

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

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

        if (!code_repositories) {
            return code_repositories;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.code_files_repository = await code_repositories.getCode_files_repository({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.workspace = await code_repositories.getWorkspace({
            transaction
        });
        
        
        output.files = await code_repositories.getFiles({
            transaction
        });
        
        
        output.organizations = await code_repositories.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.workspaces,
        as: 'workspace',
        
        where: filter.workspace ? {
          [Op.or]: [
            { id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.code_files,
        as: 'files',
        required: false,
      },


    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'code_repositories',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.remote_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'code_repositories',
                        'remote_url',
                        filter.remote_url,
                    ),
                };
            }
            
            if (filter.default_branch) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'code_repositories',
                        'default_branch',
                        filter.default_branch,
                    ),
                };
            }
            

            
            

            
            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.repo_type) {
                where = {
                    ...where,
                repo_type: filter.repo_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

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

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


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

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

        const records = await db.code_repositories.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,
        }));
    }

    
};

