import {
  HttpException,
  HttpStatus,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
// import { ModelService } from 'src/model/model.service';

import { ConfigService } from '@nestjs/config';
import * as dto from './dto/index';
// import { ModelService } from 'src/model/model.service';
// import * as Error from '../handler/error.exception'
import * as bcrypt from 'bcrypt';
// import { CommonService } from 'src/common/common.service';
import { toUSVString, types } from 'util';
import { Types } from 'mongoose';
import * as random_string from 'randomstring';
import { count, error, log } from 'console';
import { ModelService } from '../model/model.service';
import { CommonService } from '../common/common.service';
import moment from 'moment';
import { Pinecone } from '@pinecone-database/pinecone'
import * as path from "path";
import * as fs from "fs";
import axios from 'axios';
import { constants } from 'perf_hooks';
import { UserStatus } from '../model/schema/user.schema';

@Injectable()
export class VendorService {
  private admin_scope;
  private vendor_scope;
  private pinecone;
  private frontend_url;


  constructor(
    private readonly Model: ModelService,
    private readonly ConfigService: ConfigService,
    private readonly CommonService: CommonService // private readonly EmailService: EmailService
  ) {
    this.admin_scope = this.ConfigService.get<string>('ADMIN_SCOPE');
    this.vendor_scope = this.ConfigService.get<string>('VENDOR_SCOPE');
    this.frontend_url = this.ConfigService.get<string>('FRO_URL');
    this.pinecone = new Pinecone({
      apiKey: this.ConfigService.get<string>('PINECONE_API_KEY')
    });
  }


  signup = async (dto: dto.vendor.vendorSignup) => {
    try {
      let { email, password, name, fcm_token, phone_no, country_code } = dto;
      let find_data = await this.Model.UserModel.findOne({ email: email.toLowerCase() });
      if (find_data) throw new HttpException("Email Already Exist.", HttpStatus.BAD_REQUEST)
      // console.log("password", password);

      let hash = await bcrypt.hash(password, 10);
      let otp = await this.CommonService.GenerateOtp()
      let data_to_save = {
        email_otp: Number(otp),
        type: "VENDOR",
        name: name,
        email: email.toLowerCase(),
        profile_pic: null,
        password: hash,
        phone_no: phone_no,
        country_code: country_code,
        created_at: +new Date(),
      };
      let create = await this.Model.UserModel.create(data_to_save);

      let query = { _id: create._id };
      let projection = {
        password: false,
        super_admin: false
      };
      let options = { lean: true };
      let find = await this.Model.UserModel.findOne(query, projection, options);
      let token_payload = {
        _id: find._id,
        scope: this.vendor_scope,
        token_gen_at: +new Date(),
      };
      let token = await this.CommonService.generate_token(token_payload);
      let save_session = await this.CommonService.create_vendor_session(
        dto,
        token_payload,
        token
      )
      find['access_token'] = token;
      this.send_email_verification({ email: email.toLowerCase(), otp: otp })
      return find
    } catch (err) {
      throw err;
    }
  };

  async send_email_verification(data: any) {
    try {
      let { email, otp } = data
      otp.toString()
      let file_path = path.resolve(__dirname, './assets/email_templates/email_verification.html');
      let html = fs.readFileSync(file_path, { encoding: 'utf-8' });
      html = html.replace('%OTP_1%', otp[0]);
      html = html.replace('%OTP_2%', otp[1]);
      html = html.replace('%OTP_3%', otp[2]);
      html = html.replace('%OTP_4%', otp[3]);
      let subject = "Qixs verification email"

      await this.CommonService.send_email(email, subject, html)
    } catch (error) {
      throw error
    }
  }

  login = async (dto: dto.vendor.vendorLogin) => {
    try {
      let { password, email } = dto;

      let query = {
        email: email.toLowerCase()
      }

      const vendor = await this.Model.UserModel.findOne(query, {}, { lean: true })
      console.log("data", vendor);

      if (!vendor) throw new HttpException("Oops! It looks like your login details are incorrect. Please try again.", HttpStatus.BAD_REQUEST)
      let { password: hash } = vendor
      console.log("password", password);

      let decode = await bcrypt.compare(password, hash);
      if (decode != true) {
        throw new HttpException('Oops! The password you entered is incorrect. Please try again.', HttpStatus.BAD_REQUEST);
      } else if (vendor.status == UserStatus.BLOCK) {
        throw new HttpException('Oops! Your account is blocked by admin. Please contact admin.', HttpStatus.BAD_REQUEST);
      } else {
        let vendor_response = await this.make_vendor_response(vendor?._id.toString())
        let token_payload = {
          _id: vendor?._id,
          scope: this.vendor_scope,
          token_gen_at: +new Date(),
        };
        let token = await this.CommonService.generate_token(token_payload);
        let save_session = await this.CommonService.create_vendor_session(
          dto,
          token_payload,
          token
        );
        vendor_response['access_token'] = token;
        return vendor_response;
      }
    } catch (err) {
      throw err;
    }
  };

  async resend_otp(req: any) {
    try {
      let { _id: vendor_id, email } = req.user_data
      let otp = await this.CommonService.GenerateOtp()
      let data_to_update = {
        email_otp: Number(otp)
      };
      await this.Model.UserModel.findByIdAndUpdate(new Types.ObjectId(vendor_id), data_to_update, { new: true });
      this.send_email_verification({ email: email.toLowerCase(), otp: otp })
      return { message: "success" }
    } catch (error) {
      throw error
    }
  }

  async verify_otp(body: dto.vendor.verifyOtp, req: any) {
    try {
      let { _id: vendor_id } = req.user_data
      let { otp } = body
      let user_data = await this.Model.UserModel.findById(new Types.ObjectId(vendor_id), {}, { new: true });
      let { email_otp } = user_data

      if (Number(otp) != Number(email_otp)) throw new HttpException("Your otp is wrong", HttpStatus.BAD_REQUEST)
      let data_to_update = {
        is_email_verified: true,
        email_otp: 0
      }
      await this.Model.UserModel.findByIdAndUpdate(new Types.ObjectId(vendor_id), data_to_update, { new: true })
      return { message: "success" }
    } catch (error) {
      throw error
    }
  }

  async forget_password(dto: dto.vendor.forgetPassword) {
    try {
      let { email } = dto
      let user_data = await this.Model.UserModel.findOne({ email: email.toLowerCase() }, {}, { new: true });
      if (!user_data) throw new HttpException("User not exist", HttpStatus.BAD_REQUEST)
      let otp = await this.CommonService.GenerateOtp()
      let data_to_update = {
        email_otp: Number(otp)
      };
      await this.Model.UserModel.findOneAndUpdate({ _id: user_data._id }, data_to_update, { new: true });

      this.send_email_verification({ email: email.toLowerCase(), otp: otp })
      return { message: "success" }
    } catch (error) {
      throw error
    }
  }

  async verify_otp_forget_password(body: dto.vendor.forgetPasswordOtpVerify) {
    try {
      let { otp, email } = body
      let user_data = await this.Model.UserModel.findOne({ email: email.toLowerCase() }, {}, { new: true });
      if (!user_data) throw new HttpException("User not exist", HttpStatus.BAD_REQUEST)

      let { email_otp } = user_data

      if (Number(otp) != Number(email_otp)) throw new HttpException("Your otp is wrong", HttpStatus.BAD_REQUEST)
      let data_to_update = {
        email_otp: 0
      }
      await this.Model.UserModel.findByIdAndUpdate(user_data._id, data_to_update, { new: true })
      return { message: "success" }
    } catch (error) {
      throw error
    }
  }

  async reset_password(body: dto.vendor.updateForgetPassword) {
    try {
      let { password, email } = body
      let user_data = await this.Model.UserModel.findOne({ email: email.toLowerCase() }, {}, { new: true });
      if (!user_data) throw new HttpException("User not exist", HttpStatus.BAD_REQUEST)

      let hash = await bcrypt.hash(password, 10);
      let data_to_update = {
        password: hash
      }
      await this.Model.UserModel.findByIdAndUpdate(user_data._id, data_to_update, { new: true })
      return { message: "success" }
    } catch (error) {
      throw error
    }
  }
  admin_profile = async (request: dto.adminData) => {
    try {
      // console.log("admin_data.....", request.user_data);
      let { _id } = request.user_data;
      let query = { _id: new Types.ObjectId(_id) };
      let options = { lean: true };
      let response = await this.Model.UserModel.findOne(
        query,
        { _v: 0 },
        options
      );
      // console.log("respodne.....", response);
      let workspace = await this.vendor_workspaces(_id.toString())
      const subscription = await this.Model.subscriptionModel.findOne(
        { workspace_id: new Types.ObjectId(workspace.data.workspace_id._id), is_active: true },
        { plan_name: true, chat_token_limit: true, agent_limit_left: true, tele_duration_limit_left: true, workspace_member_limit_left: true, benifites: true, },
        { lean: true }
      );
      Object.assign(response, {
        workspace: workspace?.data,
        subscription: subscription,
        vendor_data: workspace?.vendor_roles,
      });

      response['is_subscribed'] = subscription ? true : false;

      return response;
    } catch (err) {
      throw err;
    }
  };

  make_vendor_response = async (vendor_id: string) => {
    try {
      let response = await this.Model.UserModel.findOne(
        { _id: new Types.ObjectId(vendor_id) },
        { password: 0 },
        { lean: true }
      );
      // console.log("respodne.....", response);
      return response;
    } catch (err) {
      throw err;
    }
  };


  super_admin_profile = async () => {
    try {
      // console.log("admin_data.....", request.user_data);
      // let { _id } = request.user_data;
      // let query = { _id: new Types.ObjectId(_id) };
      let options = { lean: true };
      let response = await this.Model.UserModel.findOne(
        { super_admin: true },
        { _v: 0 },
        options
      );
      // console.log("respodne.....", response);
      return response;
    } catch (err) {
      throw err;
    }
  };

  edit_profile = async (query_data: dto.editProfile, request: dto.adminData) => {
    try {
      let { name, profile_pic, company_color, company_logo, company_name, company_url, phone_no, country_code, ai_call_notification, ai_chat_notification, ai_human_notification } = query_data;
      let { _id } = request.user_data;
      let query = { _id: new Types.ObjectId(_id) };

      let data_to_update: any = {
        ...(company_url && { company_url: company_url }),
        ...(company_color && { company_color: company_color }),
        ...(company_logo && { company_logo: company_logo }),
        ...(company_name && { company_name: company_name }),
        ...(phone_no && { phone_no: phone_no }),
        ...(country_code && { country_code: country_code }),
        updated_at: +new Date()
      };
      if (ai_call_notification !== undefined && ai_call_notification !== null) {
        data_to_update.ai_call_notification = ai_call_notification;
      }
      if (ai_chat_notification !== undefined && ai_chat_notification !== null) {
        data_to_update.ai_chat_notification = ai_chat_notification;
      }
      if (ai_human_notification !== undefined && ai_human_notification !== null) {
        data_to_update.ai_human_notification = ai_human_notification;
      }
      // Update name if provided
      if (name !== undefined) {
        data_to_update.name = name;
      }
      // Update profile_pic if provided, including explicitly setting it to null
      if (profile_pic !== undefined) {
        data_to_update.profile_pic = profile_pic;
      }

      let options = { new: true };
      let response = await this.Model.UserModel.findOneAndUpdate(
        query,
        data_to_update,
        options
      );

      return response;
    } catch (err) {
      throw err;
    }
  };

  workspace_create = async (dto: dto.vendor.workspaceCreate, req: any) => {
    try {
      const { _id, email } = req.user_data;
      const { name, image, description } = dto;
      const index_name = name.toLowerCase();

      const createWorkspace = async () => {
        const newWorkspace = await this.Model.WorkspaceModel.create({
          index_name,
          name,
          description,
          created_by: new Types.ObjectId(_id),
          image,
        });
  
        // Assign roles and manage user workspace
        await this.Model.AllUserWorkspaceModel.create({
          role: "OWNER",
          workspace_id: newWorkspace._id,
          email: email.toLowerCase(),
          vendor_id: new Types.ObjectId(_id),
        });
  
        await this.Model.UserWorkspaceModel.deleteMany({ vendor_id: new Types.ObjectId(_id) });
        await this.Model.UserWorkspaceModel.create({
          workspace_id: newWorkspace._id,
          vendor_id: new Types.ObjectId(_id),
          index_name: name,
        });
  
        return newWorkspace;
      };
  
      // Check if workspace name already exists
      const existingWorkspace = await this.Model.WorkspaceModel.findOne({ index_name });
      if (existingWorkspace) {
        throw new HttpException(
          `A workspace with the name '${name}' already exists. Please try a different name.`,
          HttpStatus.BAD_REQUEST
        );
      }
  
      const workspaces = await this.Model.WorkspaceModel.find(
        { created_by: new Types.ObjectId(_id) },
        { _id: 1, name: 1 },
        { lean: true }
      );
      console.log('workspaces', workspaces.length)
  
      // If no workspaces are found, create one immediately
      if (workspaces.length === 0) {
        return await createWorkspace();
      }
  
      // Check for existing workspaces without active subscriptions
      for (const workspace of workspaces) {
        const activeSubscription = await this.Model.subscriptionModel.findOne({
          workspace_id: workspace._id,
          is_active: true,
        });
  
        if (!activeSubscription) {
          throw new HttpException(
            `You already have a workspace named '${workspace.name}' without an active subscription. Please purchase a subscription to proceed.`,
            HttpStatus.BAD_REQUEST
          );
        }
      }
  
      // Create workspace after checks
      return await createWorkspace();
    } catch (err) {
      console.error("Error creating workspace:", err);
      throw err;
    }
  };

  get_secret_key = async (key: string) => {
    try {
      if (key) {
        let data = await this.Model.workspaceKeysModel.findOne({ key: key?.toLowerCase() }, {}, { lean: true })
        if (data) {
          this.get_secret_key(null)
        } else {
          return key.toLowerCase()
        }
      }
      let count = await this.Model.workspaceKeysModel.countDocuments()
      let gen_key = await this.CommonService.genSecretKey(count)
      console.log("gen_key", gen_key);

      return await this.get_secret_key(gen_key)
    } catch (error) {
      throw error
    }
  }

  workspace_edit = async (workspace_id: string, dto: dto.vendor.workspaceEdit, req: any) => {
    try {
      let { _id, email } = req.user_data;
      let { image, name } = dto
      let get_data = await this.Model.WorkspaceModel.findOneAndUpdate(
        {
          _id: new Types.ObjectId(workspace_id),
          created_by: new Types.ObjectId(_id),
        },
        {
          ...(image != undefined && { image: image }),
          ...(name && { name: name }),
        },
        {
          new: true,
          lean: true
        }
      )
      if (!get_data) throw new HttpException("You cat not update. only owner can", HttpStatus.BAD_REQUEST)
      return get_data;
    } catch (err) {
      throw err;
    }
  };

  async vendor_workspaces(vendor_id: string) {
    try {
      let data: any = await this.Model.UserWorkspaceModel.findOne({ vendor_id: new Types.ObjectId(vendor_id) }, {}, { lean: true }).populate([{ path: "workspace_id", populate: [{ path: "created_by", select: "name profile_pic" }] }])
      let vendor_roles = await this.Model.AllUserWorkspaceModel.findOne({ vendor_id: new Types.ObjectId(vendor_id), workspace_id: data?.workspace_id?._id }, {}, { lean: true })

      return { data, vendor_roles }
    } catch (error) {
      throw error
    }
  }

  async get_vendor_workspaces(dto: dto.vendor.get_workspace, req: any) {
    try {
      let { _id: vendor_id, email } = req.user_data;
      let { pagination, limit } = dto
      let options = await this.CommonService.set_options(pagination, limit)
      let query = {
        $or: [
          { vendor_id: new Types.ObjectId(vendor_id) },
          { email: email.toLowerCase() }
        ]
      }
      let data = await this.Model.AllUserWorkspaceModel.find(
        query, {}, options).populate([{ path: "workspace_id" }])
      let count = await this.Model.AllUserWorkspaceModel.countDocuments(query)
      return { count, data }

    } catch (error) {
      throw error
    }
  }

  async get_workspace_detail(workspace_id: string, req: any) {
    try {
      let data = await this.Model.WorkspaceModel.findOne({ _id: new Types.ObjectId(workspace_id) }, {}, { lean: true })
      return data
    } catch (error) {
      throw error
    }
  }

  async get_workspaces_keys(workspace_id: string, req: any) {
    try {
      let { _id: vendor_id, email } = req.user_data;
      let get_workspace = await this.Model.AllUserWorkspaceModel.findOne({
        $or: [
          { vendor_id: new Types.ObjectId(vendor_id), },
          { email: email.toLowerCase() }
        ],
        workspace_id: new Types.ObjectId(workspace_id)
      }, {}, { lean: true })
      if (!get_workspace) throw new HttpException("You are not in workspace", HttpStatus.BAD_REQUEST)

      let data = await this.Model.workspaceKeysModel.find({ workspace_id: new Types.ObjectId(workspace_id) }, {}, { lean: true })
      return data
    } catch (error) {
      throw error
    }
  }

  async changePassword(body: dto.adminChangePass, request: dto.adminData) {
    try {
      let { oldPassword, newPassword } = body;
      let { _id: admin_id } = request.user_data;
      let query = { _id: admin_id };
      let projection = { __v: 0 };
      let options = { lean: true };
      let admin = await this.Model.UserModel.find(query, projection, options);
      // console.log(admin);
      if (admin.length) {
        let { _id, password } = admin[0];
        let decrypt = await bcrypt.compare(oldPassword, password);
        // console.log("password compare....", decrypt);

        if (decrypt != true) {
          throw new HttpException(
            'The current password you entered is incorrect. Please try again.',
            HttpStatus.BAD_REQUEST
          );
        } else {
          let pass_repeat = await bcrypt.compare(newPassword, password);
          // console.log("pass_repeat----->", pass_repeat)
          // console.log("pass_repeat------>1")
          if (pass_repeat) {
            // console.log("pass_repeat------>2")
            throw new HttpException(
              "Your new password matches your old password. To ensure your account's security, please choose a new and unique password.",
              HttpStatus.BAD_REQUEST
            );
          } else {
            let bycryt_password = await bcrypt.hash(newPassword, 10);
            let query = { _id: _id };
            let update = { password: bycryt_password };
            let options = {
              projection: {
                super_admin: 0,
                is_blocked: 0,
                is_deleted: 0,
                password: 0,
                __v: 0,
              },
              new: true,
            };
            let response = await this.Model.UserModel.findOneAndUpdate(
              query,
              update,
              options
            );
            return response;
          }
        }
      } else {
        throw new UnauthorizedException();
      }
    } catch (err) {
      throw err;
    }
  }

  login_exisitng_admin = async (admin: any, body: dto.vendor.vendorLogin) => {
    try {
      let { _id, password: hash } = admin;
      let { password } = body;
      // console.log(hash, password);

      let decode = await bcrypt.compare(password, hash);
      // console.log(`🚀 ~ file: admin.service.ts:23 ~ AdminService ~ login ~ decode:`, decode)
      if (decode != true) {
        throw new HttpException('Wrong password', HttpStatus.BAD_REQUEST);
      } else {
        // ! update admin
        let query = { _id: _id };
        let update = { updated_at: +new Date() };
        let options = {
          projection: {
            name: 1,
            profile_pic: 1,
            email: 1,
            super_admin: 1,
            roles: 1,
            updated_at: 1,
            created_at: 1,
          },
          new: true,
          lean: true,
        };
        let update_admin = await this.Model.UserModel.findOneAndUpdate(
          query,
          update,
          options
        );
        let token_payload = {
          _id: _id,
          scope: this.admin_scope,
          token_gen_at: +new Date(),
        };
        let token = await this.CommonService.generate_token(token_payload);
        let save_session = await this.CommonService.create_admin_session(
          body,
          token_payload,
          token
        );
        update_admin['access_token'] = token;
        // update_admin.message = "Logged in"
        return update_admin;
      }
    } catch (err) {
      throw err;
    }
  };

  create_new_admin = async (body: dto.vendor.vendorLogin) => {
    try {
      let { email, password } = body;
      if (email.toLowerCase() != 'admin@gmail.com') {
        throw new HttpException(
          `Please enter valid Email Address`,
          HttpStatus.BAD_REQUEST
        );
      }
      let hash = await bcrypt.hash('qwerty', 10);
      let data_to_save = {
        // type: "ADMIN",
        name: 'super admin',
        email: 'admin@gmail.com',
        profile_pic: null,
        password: hash,
        super_admin: true,
        created_at: +new Date(),
      };
      let create = await this.Model.UserModel.create(data_to_save);

      let query = { _id: create._id };
      let projection = {
        email: true,
        name: true,
        super_admin: true,
        roles: true,
        profile_pic: true,
        updated_at: true,
        created_at: true,
      };
      let options = { lean: true };
      let find = await this.Model.UserModel.findOne(query, projection, options);
      let token_payload = {
        _id: find._id,
        scope: this.admin_scope,
        token_gen_at: +new Date(),
      };
      let token = await this.CommonService.generate_token(token_payload);
      let save_session = await this.CommonService.create_admin_session(
        body,
        token_payload,
        token
      );
      find['access_token'] = token;
      return find;
    } catch (err) {
      throw err;
    }
  };

  // create_driver = async (body: dto.driver_signup) => {
  //     try {
  //         let {email}=body
  //         let existingDriver = await this.Model.UserModel.findOne({ email: email },{__v:0},{lean:true});
  //         if (existingDriver) {
  //             throw new HttpException('Email already exists',HttpStatus.BAD_REQUEST);
  //         }
  //         let pass: any = await this.generate_product_id();
  //         console.log("genertepass----------->", pass);
  //         let encrypt_pass = await this.CommonService.encriptPass(pass.toString());
  //         console.log("encrypt_pass", encrypt_pass);
  //         let payload: any = {
  //             email,
  //             pass
  //         };
  //         await this.EmailService.send_welcome_email_driver(payload);
  //         let data_to_save = {
  //             type:"DRIVER",
  //             email: email.toLowerCase(),
  //             password: encrypt_pass,
  //             is_email_verified:true
  //         };
  //         let driver = await this.Model.UserModel.create(data_to_save);
  //         console.log("driver---------------->",driver);

  //         return driver;
  //     } catch (error) {
  //         throw error;
  //     }
  // };

  async generate_product_id() {
    try {
      let static_value = 'ORDER';
      let options = {
        length: 6,
        charset: 'alphanumeric',
        capitalization: 'uppercase',
      };
      let random_value = random_string.generate(options);

      return random_value;
    } catch (error) {
      throw error;
    }
  }

  async call_list(body: dto.call.callList, req: any) {
    try {
      const { _id: vendor_id } = req.user_data;
      let { pagination, limit, type, status, search } = body
      let option = await this.CommonService.set_options(pagination, limit);
      const find_workspace = await this.Model.UserWorkspaceModel.findOne({
        vendor_id: new Types.ObjectId(vendor_id),
      })
      let query = {
        workspace_id: find_workspace?.workspace_id,
        ...(type && { type: type }),
        ...(status && { status: status }),
        ...(search && {
          $or: [
            { name: { $regex: search, $options: "i" } },
            { email: { $regex: search, $options: "i" } },
            { phone_no: { $regex: search, $options: "i" } }]
        })

      }
      let data = await this.Model.CallModel.find(query, {}, option).populate([{ path: 'agent_id', select: 'name image' }])
      let count = await this.Model.CallModel.countDocuments(query)
      return { data, count }
    } catch (error) {
      throw error;
    }
  }


  async call_detail(call_id: string) {
    try {
      let query = {
        _id: new Types.ObjectId(call_id)
      }
      let data = await this.Model.CallModel.find(query, {}, { lean: true }).populate([{ path: 'agent_id', select: 'name image' }])
      return data
    } catch (error) {
      throw error;
    }
  }

  async call_transcript(call_id: string) {
    try {
      let query = {
        call_id: new Types.ObjectId(call_id)
      }
      let data = await this.Model.CallTranscriptModel.find(query, {}, { sort: { _id: 1 } })
      return { data }
    } catch (error) {
      throw error;
    }
  }

  async voice_chat_transcript(chat_id: string) {
    try {
      let query = {
        chat_id: new Types.ObjectId(chat_id)
      }
      let data = await this.Model.landingPageChatHistoryModel.find(query, {}, { sort: { _id: 1 } })
      return { data }
    } catch (error) {
      throw error;
    }
  }

  async dashboard_old(body: dto.DashboardApi, req: any) {
    try {
      const { type } = body
      const { _id: vendor_id } = req.user_data;

      let find_workspace = await this.Model.UserWorkspaceModel.findOne({
        vendor_id: new Types.ObjectId(vendor_id),
      })
      // if (!find_workspace) throw new HttpException("You ar Not in this workspace", HttpStatus.BAD_REQUEST)

      let start_time = moment().startOf('year').valueOf();
      let end_time = moment().endOf('year').valueOf();
      if (type == "YEAR") {
        start_time = moment().startOf('year').valueOf();
        end_time = moment().endOf('year').valueOf();
      } else if (type == "MONTH") {
        start_time = moment().startOf('month').valueOf();
        end_time = moment().endOf('month').valueOf();
      } else if (type == "WEAK") {

        start_time = moment().startOf('week').valueOf();
        end_time = moment().endOf('week').valueOf();

      } else if (type == "TODAY") {
        start_time = moment().startOf('day').valueOf();
        end_time = moment().endOf('day').valueOf();

      }

      console.log('start_time', start_time)
      console.log('end_time', end_time)


      let active_call = await this.Model.CallModel.countDocuments({
        type: "CALL",
        status: "ACTIVE",
        workspace_id: find_workspace?.workspace_id,
        $and: [
          { created_at: { $gte: start_time, } },
          { created_at: { $lte: end_time, } },

        ]
      })

      let total_call = await this.Model.CallModel.countDocuments({
        type: "CALL",
        workspace_id: find_workspace?.workspace_id,
        $and: [
          { created_at: { $gte: start_time, } },
          { created_at: { $lte: end_time, } },

        ]
      })

      let total_chat = await this.Model.CallModel.countDocuments({
        type: "CHAT",
        workspace_id: find_workspace?.workspace_id,
        $and: [
          { created_at: { $gte: start_time, } },
          { created_at: { $lte: end_time, } },

        ]
      })

      let active_chat = await this.Model.CallModel.countDocuments({
        workspace_id: find_workspace?.workspace_id,
        type: "CHAT",
        status: "ACTIVE"
      })
      return { active_call, total_call, total_chat, active_chat }
    } catch (error) {
      throw error;
    }
  }

  async dashboard(body: dto.DashboardApi, req: any) {
    try {
      const { type } = body;
      const { _id: vendor_id } = req.user_data;

      const workspace = await this.Model.UserWorkspaceModel.findOne({
        vendor_id: new Types.ObjectId(vendor_id),
      });
      if (!workspace) {
        throw new HttpException("Workspace not found for the vendor", HttpStatus.BAD_REQUEST);
      }

      let start_time: number;
      let end_time: number;

      const getTimeRange = (type: string) => {
        switch (type) {
          case "YEAR":
            return [moment().startOf('year').valueOf(), moment().endOf('year').valueOf()];
          case "MONTH":
            return [moment().startOf('month').valueOf(), moment().endOf('month').valueOf()];
          case "WEEK":
            return [moment().startOf('week').valueOf(), moment().endOf('week').valueOf()];
          case "TODAY":
            return [moment().startOf('day').valueOf(), moment().endOf('day').valueOf()];
          default:
            return [moment().startOf('year').valueOf(), moment().endOf('year').valueOf()];
        }
      };

      [start_time, end_time] = getTimeRange(type);

      const timeFilter = {
        created_at: { $gte: start_time, $lte: end_time },
        workspace_id: workspace?.workspace_id,
      };

      const total_tele_call = await this.Model.CallModel.countDocuments({
        type: "CALL",
        ...timeFilter,
      });

      const total_chat = await this.Model.CallModel.countDocuments({
        type: "CHAT",
        ...timeFilter,
      });

      const total_call = await this.Model.CallModel.countDocuments({
        type: "VOICE_CHAT",
        ...timeFilter,
      });

      const active_tele_call = await this.Model.CallModel.countDocuments({
        type: "CALL",
        status: "ACTIVE",
        workspace_id: workspace?.workspace_id,
      });

      const active_chat = await this.Model.CallModel.countDocuments({
        type: "CHAT",
        status: "ACTIVE",
        workspace_id: workspace?.workspace_id,
      });

      const active_call = await this.Model.CallModel.countDocuments({
        type: "VOICE_CHAT",
        status: "ACTIVE",
        workspace_id: workspace?.workspace_id,
      });

      const stats = {
        active_tele_call: active_tele_call || 0,
        total_tele_call: total_tele_call || 0,
        active_call: active_call || 0,
        total_call: total_call || 0,
        total_chat: total_chat || 0,
        active_chat: active_chat || 0,
      };

      return stats;
    } catch (error) {
      console.error('Error in dashboard API:', error);
      throw error;
    }
  }




  async dashboard_chat_count(body: dto.DashboardApi, req: any) {
    try {
      let { type } = body
      let { _id: vendor_id } = req.user_data;

      let find_workspace = await this.Model.UserWorkspaceModel.findOne({
        vendor_id: new Types.ObjectId(vendor_id),
      })
      let start_time = moment().startOf('year').valueOf();
      let end_time = moment().endOf('year').valueOf();
      if (type == "YEAR") {
        start_time = moment().startOf('year').valueOf();
        end_time = moment().endOf('year').valueOf();
      } else if (type == "MONTH") {
        start_time = moment().startOf('month').valueOf();
        end_time = moment().endOf('month').valueOf();
      } else if (type == "WEAK") {

        start_time = moment().startOf('week').valueOf();
        end_time = moment().endOf('week').valueOf();

      } else if (type == "TODAY") {
        start_time = moment().startOf('day').valueOf();
        end_time = moment().endOf('day').valueOf();

      }


      let total_chat = await this.Model.CallModel.countDocuments({
        type: "CHAT",
        workspace_id: find_workspace?.workspace_id,
        $and: [
          { created_at: { $gte: start_time, } },
          { created_at: { $lte: end_time, } },
        ]
      })

      return { total_chat }
    } catch (error) {
      throw error;
    }
  }


  get_users = async (query_data: dto.pl, request: dto.adminData) => {
    try {
      let { pagination, limit } = query_data;
      let { _id } = request.user_data;
      let user_workspace = await this.Model.UserWorkspaceModel.findOne({ vendor_id: new Types.ObjectId(_id) })
      if (!user_workspace) throw new HttpException("You are not in workspace", HttpStatus.BAD_REQUEST)
      let option = await this.CommonService.set_options(pagination, limit)
      let response = await this.Model.AllUserWorkspaceModel.find(
        { workspace_id: user_workspace?.workspace_id },
        {},
        option
      ).populate([{ path: "vendor_id", select: "name email profile_pic" }])
      let count = await this.Model.AllUserWorkspaceModel.countDocuments({ workspace_id: user_workspace?.workspace_id })
      return { count: count, data: response };
    } catch (err) {
      throw err;
    }
  };

  invite_user_in_workspace = async (wokspace_id: string, body: dto.vendor.vendor_email, req: any) => {
    try {
      let { _id } = req.user_data;
      let { email, role, vendor_roles } = body

      const subscription = await this.Model.subscriptionModel.findOne({
        workspace_id: new Types.ObjectId(wokspace_id),
        is_active: true
      });
      if (!subscription) throw new HttpException(`You don't have any subscription plan! Please purchase any subscription.`, HttpStatus.BAD_REQUEST);

      if (subscription.workspace_member_limit_left === 0) {
        throw new HttpException(`You have reached your workspace member limits.`, HttpStatus.BAD_REQUEST);
      }

      let user_join = await this.Model.AllUserWorkspaceModel.findOne({
        workspace_id: new Types.ObjectId(wokspace_id),
        email: email.toLowerCase(),
      })

      if (user_join) throw new HttpException("You already invite this email", HttpStatus.BAD_REQUEST)

      let user_data = await this.Model.UserModel.findOne({ email: email.toLowerCase() }, {}, { lean: true })
      this.send_invite_email({ email: email, wokspace_id: wokspace_id })
      const result = await this.Model.AllUserWorkspaceModel.create({
        workspace_id: new Types.ObjectId(wokspace_id),
        email: email.toLowerCase(),
        ...(user_data && { vendor_id: user_data._id }),
        role: role,
        is_invite: true,
        vendor_roles: vendor_roles,
        status: "INVITE"
      });
      // deduct limits
      await this.Model.subscriptionModel.findOneAndUpdate({ _id: subscription._id }, { workspace_member_limit_left: (subscription.workspace_member_limit_left - 1) }, { new: true })
      return result;
    } catch (err) {
      throw err;
    }
  }

  async send_invite_email(data: any) {
    try {
      const { email, wokspace_id } = data

      let subject = "Invite vendor in workspace"

      let file_path = path.resolve(__dirname, './assets/email_templates/invitation_link.html');
      let html = fs.readFileSync(file_path, { encoding: 'utf-8' });
      html = html.replace('%url%', this.frontend_url + wokspace_id);
      await this.CommonService.send_email(email, subject, html)
    } catch (error) {
      throw error
    }
  }

  resend_invite_user_in_workspace = async (wokspace_id: string, body: dto.vendor.resend_invite, req: any) => {
    try {
      // let { _id } = req.user_data;
      let { email } = body
      let user_join = await this.Model.AllUserWorkspaceModel.findOne({
        workspace_id: new Types.ObjectId(wokspace_id),
        email: email.toLowerCase(),
      })

      if (!user_join) throw new HttpException("user not in workspace please invite user", HttpStatus.BAD_REQUEST)
      this.send_invite_email({ email: email, wokspace_id: wokspace_id })
      return "success invite"
    } catch (err) {
      throw err;
    }
  }

  vendor_workspace_join = async (wokspace_id: string, req: any) => {
    try {
      let { _id, email } = req.user_data;

      let user_workspace = await this.Model.AllUserWorkspaceModel.findOne({
        workspace_id: new Types.ObjectId(wokspace_id),
        $or: [{ vendor_id: new Types.ObjectId(_id) }, { email: email.toLowerCase() }]
      })
      if (!user_workspace) throw new HttpException("You ar Not in this workspace", HttpStatus.BAD_REQUEST)
      let data = await this.Model.UserWorkspaceModel.deleteMany({ vendor_id: new Types.ObjectId(_id) })
      // console.log("dalete data", data);

      await this.Model.AllUserWorkspaceModel.updateMany({ email: email.toLowerCase() }, { vendor_id: new Types.ObjectId(_id), status: "ACTIVE", is_invite: false })
      let create = await this.Model.UserWorkspaceModel.create({
        workspace_id: new Types.ObjectId(wokspace_id),
        vendor_id: new Types.ObjectId(_id),
      })
      console.log("create", create);

      return create
    } catch (err) {
      throw err;
    }
  }


  workspace_role_change = async (wokspace_id: string, body: dto.vendor.workspace_role_change, req: any) => {
    try {
      let { _id, email } = req.user_data;
      let { role, email: user_email, status, vendor_roles } = body

      let user_join = await this.Model.AllUserWorkspaceModel.findOne({
        workspace_id: new Types.ObjectId(wokspace_id),
        $or: [{ email: email.toLowerCase() }, { vendor_id: _id }]
      })

      if (!user_join) throw new HttpException("You are not in workspace", HttpStatus.BAD_REQUEST)

      if (role = "ADMIN") {
        if (user_join.role == "OWNER" || user_join.role == "ADMIN") {
          return await this.Model.AllUserWorkspaceModel.findOneAndUpdate({
            workspace_id: new Types.ObjectId(wokspace_id),
            email: user_email.toLowerCase()
          },
            {
              ...(role && { role: role }),
              // ...(status&&{status: status}),
              ...(vendor_roles?.length && { vendor_roles: vendor_roles }),
            },
            {
              new: true, lean: true
            })
        } else {
          throw new HttpException("you are not admin", HttpStatus.BAD_REQUEST)
        }

      }


      if (role = "MEMBER") {
        if (user_join.role == "OWNER") {
          return await this.Model.AllUserWorkspaceModel.findOneAndUpdate({
            workspace_id: new Types.ObjectId(wokspace_id),
            email: email.toLowerCase()
          },
            {
              role: role,
              ...(vendor_roles?.length && { vendor_roles: vendor_roles }),
              // ...(status&&{status: status}),
            },
            {
              new: true, lean: true
            })
        } else {
          throw new HttpException("you are not owner", HttpStatus.BAD_REQUEST)
        }

      }

      if (status) {
        if (user_join.role == "OWNER") {
          return await this.Model.AllUserWorkspaceModel.findOneAndUpdate({
            workspace_id: new Types.ObjectId(wokspace_id),
            email: user_email.toLowerCase()
          },
            {
              ...(status && { status: status }),
            },
            {
              new: true, lean: true
            })
        } else {
          throw new HttpException("you are not owner", HttpStatus.BAD_REQUEST)
        }
      }
      let user_data = await this.Model.UserModel.findOne({ email: email.toLowerCase() }, {}, { lean: true })
      return await this.Model.AllUserWorkspaceModel.create({
        workspace_id: new Types.ObjectId(wokspace_id),
        email: email.toLowerCase(),
        ...(user_data && { vendor_id: user_data._id }),
        role: "MEMBER"
      })
    } catch (err) {
      throw err;
    }
  }



  delete_workspace = async (workspace_id: string, body: dto.vendor.vendor_password, req: any) => {
    try {
      let { _id } = req.user_data;
      let user_data = await this.Model.UserModel.findOne({ _id: _id }, {}, { lean: true })
      let { password } = body


      let decode = await bcrypt.compare(password, user_data?.password);
      if (decode != true) {
        throw new HttpException('Wrong password', HttpStatus.BAD_REQUEST);
      }
      let workspcae = await this.Model.WorkspaceModel.findOne(
        {
          _id: new Types.ObjectId(workspace_id),
          created_by: new Types.ObjectId(_id)
        }
      )

      if (!workspcae) throw new HttpException("You are not owner of this workspace", HttpStatus.BAD_REQUEST)
      let data = await this.pinecone.deleteIndex(workspcae?.index_name)
      await this.Model.WorkspaceModel.deleteMany({ _id: new Types.ObjectId(workspace_id) })
      await this.Model.AllUserWorkspaceModel.deleteMany({ workspace_id: new Types.ObjectId(workspace_id) })
      await this.Model.UserWorkspaceModel.deleteMany({ workspace_id: new Types.ObjectId(workspace_id) })
      return "workspace delete successfull"
    } catch (err) {
      throw err;
    }
  };



  contact_us = async (body: dto.vendor.contact_us, req: any) => {
    try {
      let { _id } = req.user_data;
      const { name, subject, message, email, phone_no, country_code, type } = body
      return await this.Model.contactUsModel.create({
        name: name,
        subject: subject,
        message: message,
        email: email,
        phone_no: phone_no,
        country_code: country_code,
        type: type
      })

    } catch (err) {
      throw err;
    }
  };

  async workspace_script_create(workspace_id: string, body: dto.vendor.workspace_script_create, req: any) {
    try {

      let { _id: vendor_id, email } = req.user_data;
      let get_workspace = await this.Model.AllUserWorkspaceModel.findOne({
        $or: [
          { vendor_id: new Types.ObjectId(vendor_id), },
          { email: email.toLowerCase() }
        ],
        workspace_id: new Types.ObjectId(workspace_id)
      }, {}, { lean: true })
      if (!get_workspace) throw new HttpException("You are not in workspace", HttpStatus.BAD_REQUEST)

      const { agent_id, key, name, image, title, description, colour, font_colour } = body

      const is_agent_assigned: any = await this.Model.scriptModel.findOne({ agent_id: new Types.ObjectId(agent_id) }).populate({ path: 'agent_id', select: 'name' });
      if (is_agent_assigned) throw new HttpException(`The agent '${is_agent_assigned?.agent_id?.name}' is already assigned to this script. Kindly select a different agent to proceed.`, HttpStatus.BAD_REQUEST);

      let data = await this.Model.scriptModel.create({
        workspace_id: new Types.ObjectId(workspace_id),
        agent_id: new Types.ObjectId(agent_id),
        key: key,
        name: name,
        image: image,
        title: title,
        description: description,
        colour: colour,
        font_colour: font_colour,
      }, {}, { lean: true })
      return data
    } catch (error) {
      throw error
    }
  }

  async workspace_script_edit(workspace_id: string, body: dto.vendor.workspace_script_edit, req: any) {
    try {

      let { _id: vendor_id, email } = req.user_data;
      let get_workspace = await this.Model.AllUserWorkspaceModel.findOne({
        $or: [
          { vendor_id: new Types.ObjectId(vendor_id), },
          { email: email.toLowerCase() }
        ],
        workspace_id: new Types.ObjectId(workspace_id)
      }, {}, { lean: true })
      if (!get_workspace) throw new HttpException("You are not in workspace", HttpStatus.BAD_REQUEST)

      const { script_id, name, image, title, description, colour, font_colour } = body

      let data = await this.Model.scriptModel.findByIdAndUpdate(new Types.ObjectId(script_id), {

        ...(name && { name: name }),
        ...(image && { image: image }),
        ...(title && { title: title }),
        ...(description && { ndescriptioname: description }),
        ...(colour && { colour: colour }),
        ...(font_colour && { font_colour: font_colour }),
      }, { lean: true, new: true })
      return data
    } catch (error) {
      throw error
    }
  }

  async workspace_script_delete(workspace_id: string, script_id: string, req: any) {
    try {

      let { _id: vendor_id, email } = req.user_data;
      let get_workspace = await this.Model.AllUserWorkspaceModel.findOne({
        $or: [
          { vendor_id: new Types.ObjectId(vendor_id), },
          { email: email.toLowerCase() }
        ],
        workspace_id: new Types.ObjectId(workspace_id)
      }, {}, { lean: true })
      if (!get_workspace) throw new HttpException("You are not in workspace", HttpStatus.BAD_REQUEST)

      await this.Model.scriptModel.findByIdAndDelete(new Types.ObjectId(script_id))
      return "success"
    } catch (error) {
      throw error
    }
  }

  async workspace_script_detail_no_auth(script_id: string, req: any) {
    try {
      return await this.Model.scriptModel.findById(new Types.ObjectId(script_id), {}, { lean: true })
    } catch (error) {
      throw error
    }
  }

  async workspace_script_get_detail(workspace_id: string, script_id: string, req: any) {
    try {

      let { _id: vendor_id, email } = req.user_data;
      let get_workspace = await this.Model.AllUserWorkspaceModel.findOne({
        $or: [
          { vendor_id: new Types.ObjectId(vendor_id), },
          { email: email.toLowerCase() }
        ],
        workspace_id: new Types.ObjectId(workspace_id)
      }, {}, { lean: true })
      if (!get_workspace) throw new HttpException("You are not in workspace", HttpStatus.BAD_REQUEST)

      return await this.Model.scriptModel.findById(new Types.ObjectId(script_id), {}, { lean: true })

    } catch (error) {
      throw error
    }
  }

  async script_enable_disable(workspace_id: string, script_id: string, req: any, body: dto.vendor.workspace_script_status) {
    try {
      const { script_status } = body;
      const { _id: vendor_id, email } = req.user_data;
      const get_workspace = await this.Model.AllUserWorkspaceModel.findOne({
        $or: [
          { vendor_id: new Types.ObjectId(vendor_id), },
          { email: email.toLowerCase() }
        ],
        workspace_id: new Types.ObjectId(workspace_id)
      }, {}, { lean: true })
      if (!get_workspace) throw new HttpException("You are not in workspace", HttpStatus.BAD_REQUEST)

      return await this.Model.scriptModel.findOneAndUpdate({ _id: new Types.ObjectId(script_id) }, { script_status: script_status }, { new: true })

    } catch (error) {
      throw error
    }
  }

  async workspace_script_get(workspace_id: string, body: dto.vendor.get_script, req: any) {
    try {

      const { _id: vendor_id, email } = req.user_data;
      const get_workspace = await this.Model.AllUserWorkspaceModel.findOne({
        $or: [
          { vendor_id: new Types.ObjectId(vendor_id), },
          { email: email.toLowerCase() }
        ],
        workspace_id: new Types.ObjectId(workspace_id)
      }, {}, { lean: true })

      if (!get_workspace) throw new HttpException("You are not in workspace", HttpStatus.BAD_REQUEST)

      let { pagination, limit } = body
      let option = await this.CommonService.set_options(pagination, limit)

      let data = await this.Model.scriptModel.find({ workspace_id: new Types.ObjectId(workspace_id) }, {}, option).populate([{ path: 'agent_id', select: 'name image' }])
      let count = await this.Model.scriptModel.countDocuments({ workspace_id: new Types.ObjectId(workspace_id) })

      return { count: count, data: data }
    } catch (error) {
      throw error
    }
  }


  async workspace_secret_key_delete(workspace_id: string, req: any) {
    try {

      let { _id: vendor_id, email } = req.user_data;
      let get_workspace = await this.Model.AllUserWorkspaceModel.findOne({
        $or: [
          { vendor_id: new Types.ObjectId(vendor_id), },
          { email: email.toLowerCase() }
        ],
        workspace_id: new Types.ObjectId(workspace_id)
      }, {}, { lean: true })
      if (!get_workspace) throw new HttpException("You are not in workspace", HttpStatus.BAD_REQUEST)

      let data = await this.Model.workspaceKeysModel.updateMany({
        workspace_id: new Types.ObjectId(workspace_id),
      }, { is_delete: true }, { lean: true, new: true })
      return data
    } catch (error) {
      throw error
    }
  }

  async workspace_key_genrate(workspace_id: string, req: any) {
    try {
      let { _id: vendor_id, email } = req.user_data;
      let get_workspace = await this.Model.AllUserWorkspaceModel.findOne({
        $or: [
          { vendor_id: new Types.ObjectId(vendor_id), },
          { email: email.toLowerCase() }
        ],
        workspace_id: new Types.ObjectId(workspace_id)
      }, {}, { lean: true })
      if (!get_workspace) throw new HttpException("You are not in workspace", HttpStatus.BAD_REQUEST)

      let get_key = await this.Model.workspaceKeysModel.findOne({ workspace_id: new Types.ObjectId(workspace_id), is_delete: false })

      if (get_key) throw new HttpException("Already has key", HttpStatus.BAD_REQUEST)


      let key = await this.get_secret_key(null)
      console.log("key", key)
      await this.Model.workspaceKeysModel.create({ workspace_id: new Types.ObjectId(workspace_id), key: key })
    } catch (error) {
      throw error
    }
  }


  async workspace_secret_key_get(workspace_id: string, req: any) {
    try {

      let { _id: vendor_id, email } = req.user_data;
      let get_workspace = await this.Model.AllUserWorkspaceModel.findOne({
        $or: [
          { vendor_id: new Types.ObjectId(vendor_id), },
          { email: email.toLowerCase() }
        ],
        workspace_id: new Types.ObjectId(workspace_id)
      }, {}, { lean: true })
      if (!get_workspace) throw new HttpException("You are not in workspace", HttpStatus.BAD_REQUEST)

      let data = await this.Model.workspaceKeysModel.find({
        workspace_id: new Types.ObjectId(workspace_id),
        is_delete: false
      }, {}, { lean: true, new: true })
      if (!data.length) throw new HttpException("Dont have key genrate new key", HttpStatus.BAD_REQUEST)

      return data
    } catch (error) {
      throw error
    }
  }

  async white_list_form(body: dto.vendor.white_list_form, req: any) {
    try {
      const { _id: vendor_id } = req.user_data;
      const user = await this.Model.UserModel.findOne({ _id: new Types.ObjectId(vendor_id) })
      const { name, email, phone_no, country_code, message } = body;
      if (!name || !email) {
        throw new HttpException(`Name or email is required!`, HttpStatus.BAD_REQUEST)
      }

      const data = await this.Model.WhiteLableModel.create({
        user: new Types.ObjectId(vendor_id),
        name: name,
        email: email,
        message: message,
        phone_no: phone_no,
        country_code: country_code,
      });

      const url = 'https://www.zohoapis.com/crm/v2/Leads';
      const headers = {
        'Content-Type': 'application/json',
        'Authorization': `Zoho-oauthtoken ${`1000.528f9b168b90d41ddfbebbf9ad16a505.162288d5a778467419c350dbe66938ca`}`
      };

      const zoho_body_data = {
        "data": [
          {
            "Last_Name": name ? name : user?.name,
            "Email": email,
            "Description": message,
            "Website": "https://www.qixs.ai",
            "Salutation": "Mr.",
            "First_Name": name ? name : user?.name,
            "Lead_Status": "Attempted to Contact",
            "Phone": phone_no,
            "Email_Opt_Out": false,
            "Mobile": country_code + phone_no,
            "Lead_Source": "Qixs AI vender panel white label request",
            "Country": user?.country,
            "Secondary_Email": user?.email
          }
        ]
      };

      axios.post(url, zoho_body_data, { headers })
        .then(response => {
          console.log('Response:', response.data);
        })
        .catch(error => {
          console.error('Error:', error.response ? error.response.data : error.message);
        });


      return data
    } catch (error) {
      throw error
    }
  }

  async get_exist_count(req: any) {
    try {

      const { _id: vendor_id } = req.user_data;
      console.log('vendor_id', vendor_id)
      let workspace_count = 0;
      const workspace = await this.Model.AllUserWorkspaceModel.findOne(
        {
          vendor_id: new Types.ObjectId(vendor_id)
        },
        { workspace_id: 1 },
        { lean: true }
      );

      if (!workspace) { workspace_count = 0 }
      const { workspace_id } = workspace;

      console.log('workspace_id', workspace_id)
      const workspace_key_count = await this.Model.workspaceKeysModel.countDocuments({ workspace_id: workspace_id, is_delete: false });
      const knowledgebase_count = await this.Model.knowledgeBaseModel.countDocuments({ workspace_id: workspace_id })
      const agent_count = await this.Model.AgentModel.countDocuments({ workspace_id: workspace_id });

      return {
        workspace_count: workspace_count || 0,
        workspace_key_count: workspace_key_count || 0,
        knowledgebase_count: knowledgebase_count || 0,
        agent_count: agent_count || 0,
      }
    } catch (error) {
      throw error
    }
  }


}
