from collections import defaultdict
from datetime import datetime, timedelta, timezone, date
import time
from typing import List

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import delete, select,or_,func,desc
from fastapi import HTTPException, status

from src.Service.companyService import CompanyService
from src.auth.controller import update_subscription
from src.auth.service import add_subscription, get_subscription_by_company_id, update_subscription_plan, upsert_subscription
from src.core.database import DATABASE_URL
from src.models.company_user import User
from src.models.company import Company, Subscription
from src.models.application_user import ApplicationUser
from src.constants import UserType,DepartmentEnum,CompanyUserRoleEnum

from .schemas import CompanyRegistration,AddCompanyUser, CompanyUserCreate


#utils
from .utils import create_company_database,delete_company_database
from src.auth.utils import generate_password,pwd_context
from src.core.utils import generate_uuid, init_dynamic_dbcreate
#external services
from src.external.email import transporter
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta 

class CompaniesManagement(CompanyService):
    
    
    
    @staticmethod
    async def add_user_to_company(user_info:AddCompanyUser,db:AsyncSession):

        company = await CompaniesManagement.get_company_by_id(company_id=user_info.company_id,db=db)

        stmt = select(User).where(User.email == user_info.user_email ).limit(1)
        result = await db.execute(stmt)
        is_user_exists = result.scalars().first()

        if is_user_exists:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="A user with this email exists."
            )
        
    
        
        system_generated_password = generate_password()

        new_user = User(
                full_name=user_info.full_name,
                email=user_info.user_email,
                department=user_info.user_department,
                role=user_info.user_role,
                hashed_password=pwd_context.hash(system_generated_password),
                company_name=company.company_name,
                company_id= company.id
            )
        

        db.add(new_user)
        await db.commit()               
        await db.refresh(new_user)      

        company.users_count += 1

        await db.commit()               

        print(new_user.full_name,"Added")
        print("system_generated_password",system_generated_password)
        transporter.connect()
        transporter.send(user_info.user_email,f"user on boarding to for{user_info.user_email}",f"user on boarding to for{company.company_name} role:{user_info.user_role}, password: {system_generated_password}") 
        transporter.close()

        return {"message":"user added","user":new_user}
     # More flexible for month-based calculations
    @staticmethod
    def calculate_end_date(start_date: datetime, billing_cycle: str, custom_days: int = None) -> datetime:
        if billing_cycle == "yearly":
            return start_date + relativedelta(years=1)
        elif billing_cycle == "quarterly":
            return start_date + relativedelta(months=3)
        elif billing_cycle == "custom":
            if custom_days is None:
                raise ValueError("Custom days must be provided for custom billing cycle")
            return start_date + timedelta(days=custom_days)
        else:
            raise ValueError(f"Unsupported billing cycle: {billing_cycle}")
        
    @staticmethod
    async def register_company(company_info:CompanyRegistration,collabrator:int,
                bussiness_user:int,
                view_only:int, plan_id: int, name: str, billing_cycle:str, price :str,db:AsyncSession):

        try:
            print(company_info)
            db_name =None
            if not company_info.users or len(company_info.users) == 0:
                raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="At least one user must be provided.")
        
            admin_users = 0
            for user in company_info.users:
                print(user.user_department.lower(),user.user_role.lower())
                if user.user_department.lower() =="it" and user.user_role.lower() == "admin":
                    admin_users = admin_users + 1

            if admin_users == 0:
                raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="At least one user must be from IT department and role admin.")

            stmt = select(Company).where(
            or_(
                Company.email == company_info.company_email,
                Company.company_name == company_info.company_name,
                Company.legal_name == company_info.legal_name,
                Company.phone_number == company_info.company_phone_number
            ))

            result = await db.execute(stmt)
            companies = result.scalars().all()

            conflicts = []
            seen_keys = set() 

            for company in companies:
                if "email" not in seen_keys and company.email == company_info.company_email:
                    conflicts.append({"email": company.email})
                    seen_keys.add("email")

                if "company_name" not in seen_keys and company.company_name == company_info.company_name:
                    conflicts.append({"company_name": company.company_name})
                    seen_keys.add("company_name")

                if "legal_name" not in seen_keys and company.legal_name == company_info.legal_name:
                    conflicts.append({"legal_name": company.legal_name})
                    seen_keys.add("legal_name")

                if "phone_number" not in seen_keys and company.phone_number == company_info.company_phone_number:
                    conflicts.append({"phone_number": company.phone_number})
                    seen_keys.add("phone_number")

                if len(seen_keys) == 4:
                    break

            
            if conflicts:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail={
                        "message": "The following fields are already taken.",
                        "conflicts": conflicts
                    }
                )
            
            # Check for existing user emails
            for user_info in company_info.users:
                stmt = select(User).where(User.email == user_info.user_email).limit(1)
                result = await db.execute(stmt)
                existing_user = result.scalars().first()

                if existing_user:
                    conflicts.append(f"user_email:{user_info.user_email}")

            if conflicts:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=f"emails not available: {', '.join(conflicts)}"
                )
            
            db_name =await create_company_database(company_info.company_name)    
            print("db_name",db_name)
            if not db_name:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="company already exists."
                )
            
            company_id = generate_uuid()
            new_company = Company(
            id=company_id,
            company_name=company_info.company_name,
            legal_name=company_info.legal_name,
            bio=company_info.bio,
            address=company_info.address,
            home_country=company_info.home_country,
            company_logo_url=company_info.company_logo_url,
            has_branches=company_info.has_branches,
            email=company_info.company_email,
            phone_number=company_info.company_phone_number,
            db_name=db_name,
            db_host="fpna-dev-postgresql.postgres.database.azure.com",
            db_port="5432",
            plan="basic",
            next_billing_date  = datetime.now(timezone.utc) + timedelta(days=10)

            )
            
            
            db.add(new_company)
           
        
            users_count = 0

            for user in company_info.users:
            
                system_generated_password = generate_password()

                new_user = User(
                    full_name=user.full_name,
                    email=user.user_email,
                    department=user.user_department,
                    role=user.user_role,
                    hashed_password=pwd_context.hash(system_generated_password),
                    company_name=company_info.company_name,
                    company_id=company_id
                )

                db.add(new_user)
                users_count += 1
                logo_url = "https://FPnAInsights.mavenerp.in/assets/logo-transparent-png-CpxLVvxs.png"
                new_password = f'''
       <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Account Details - FPnAInsights</title>
  <script src="https://kit.fontawesome.com/your-fontawesome-kit.js" crossorigin="anonymous"></script>
</head>
<body style="background-color: #f9fafb; color: #1e293b; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; min-height: 100vh; margin: 0; padding: 1.5rem;">
  <div style="max-width: 800px; margin: 0 auto; background-color: #ffffff; box-shadow: 0 4px 12px rgba(0,0,0,0.08); border-radius: 12px; overflow: hidden; border: 1px solid #e5e7eb;">
    <!-- Header Strip -->
    <div style="height: 6px; background: linear-gradient(to right, #2563eb, #3b82f6);"></div>

    <!-- Main Content -->
    <div style="padding: 32px;">
      <!-- Logo and Header -->
      <div style="text-align: center; margin-bottom: 24px;">
        <img src="{logo_url}" alt="Logo" style="height: 48px; width: auto; margin-bottom: 16px;" />
        <h1 style="font-size: 24px; font-weight: 600; color: #111827; margin: 0 0 8px 0;">
          Welcome to Your Admin Account
        </h1>
        <p style="font-size: 14px; color: #6b7280; margin: 0; line-height: 1.5;">
          You've been granted administrator access to Formaven Group Global. Here are your secure login credentials:
        </p>
      </div>

      <!-- Credentials Section -->
      <div style="background-color: #f8fafc; border-radius: 8px; padding: 24px; margin-bottom: 24px;">
        <!-- Role and Password Side by Side -->
        <div style=" margin-bottom: 16px;">
          <!-- Role Section -->
          <div>
            <div style="font-size: 12px; font-weight: 600; color: #6b7280; text-transform: uppercase; margin-bottom: 8px; display: flex; align-items: center; gap: 6px;">
              <i class="fas fa-user-shield"></i> Role
            </div>
            <div style="padding: 12px; border-radius: 6px; background-color: #ecfdf5; color: #065f46; font-family: 'Courier New', monospace; font-size: 14px; border: 1px solid #d1fae5;">
              {new_user.role}
            </div>
          </div>

          <!-- Password Section -->
          <div>
            <div style="font-size: 12px; font-weight: 600; color: #6b7280; text-transform: uppercase; margin-bottom: 8px; display: flex; align-items: center; gap: 6px;">
              <i class="fas fa-key"></i> Temporary Password
            </div>
            <div style="padding: 12px; border-radius: 6px; background-color: #ecfdf5; color: #065f46; font-family: 'Courier New', monospace; font-size: 14px; border: 1px solid #d1fae5;">
              {system_generated_password}
            </div>
          </div>
        </div>

        <!-- Password Strength Indicator -->
        <div style="display: flex; align-items: center; gap: 8px; margin-top: 12px;">
          <div style="color: #15803d; font-size: 12px; display: flex; align-items: center; gap: 6px;">
            <i class="fas fa-shield-alt"></i> Secure auto-generated password
          </div>
          <div style="flex-grow: 1; display: flex; gap: 4px; margin-left: 8px;">
            <div style="flex: 1; height: 4px; background-color: #22c55e; border-radius: 2px;"></div>
            <div style="flex: 1; height: 4px; background-color: #22c55e; border-radius: 2px;"></div>
            <div style="flex: 1; height: 4px; background-color: #22c55e; border-radius: 2px;"></div>
            <div style="flex: 1; height: 4px; background-color: #22c55e; border-radius: 2px;"></div>
            <div style="flex: 1; height: 4px; background-color: #22c55e; border-radius: 2px;"></div>
          </div>
        </div>
      </div>

      <!-- Instructions -->
      <div style="background-color: #f8fafc; border-radius: 8px; padding: 24px; margin-bottom: 24px;">
        <h3 style="font-size: 16px; font-weight: 600; color: #111827; margin: 0 0 12px 0; display: flex; align-items: center; gap: 8px;">
          <i class="fas fa-info-circle"></i> Important Instructions
        </h3>
        <ul style="font-size: 14px; color: #4b5563; margin: 0; padding-left: 20px; line-height: 1.6;">
          <li style="margin-bottom: 8px;">Change your password immediately after first login</li>
          <li style="margin-bottom: 8px;">Do not share your credentials with anyone</li>
          <li style="margin-bottom: 8px;">Enable two-factor authentication for added security</li>
          <li>Contact support if you notice any suspicious activity</li>
        </ul>
      </div>

      <!-- Button Container -->
      <div style="text-align: center; margin-bottom: 24px;">
        <a href="https://FPnAInsights.mavenerp.in/welcome" 
           style="
             display: inline-block;
             padding: 12px 24px;
             background-color: #2563eb;
             color: white;
             text-decoration: none;
             font-weight: 600;
             border-radius: 8px;
             font-size: 16px;
             box-shadow: 0 4px 6px rgba(37, 99, 235, 0.4);
             transition: background-color 0.3s ease;
           "
           onmouseover="this.style.backgroundColor='#1e40af';" 
           onmouseout="this.style.backgroundColor='#2563eb';"
        >
          Go to Homepage
        </a>
      </div>

      <!-- Footer -->
      <div style="border-top: 1px solid #e5e7eb; padding-top: 24px; text-align: center;">
        <p style="font-size: 12px; color: #6b7280; margin: 0 0 8px 0;">
          If you're facing any issues, please contact:
          <a href="mailto:support@FPnAInsights.in" style="color: #2563eb; text-decoration: none; font-weight: 600;">support@FPnAInsights.in</a>
        </p>
        <p style="font-size: 12px; color: #6b7280; margin: 0;">
          © 2025 FPnAInsights. All rights reserved.
        </p>
      </div>
    </div>
  </div>
</body>
</html>

'''
               
                transporter.connect()
                transporter.send(user.user_email,"new password",new_password)#f"user on boarding to for{company_info.company_name}",f"user on boarding to for{company_info.company_name} role:{user.user_role}, password: {system_generated_password}") 
                transporter.close()

            new_company.users_count = users_count
            
            
            start_date = datetime.today().date()
            end_date = CompaniesManagement.calculate_end_date(start_date, billing_cycle)



            update_dict = {
                 "company_id":company_id,
                 
            "plan_id":plan_id,
            "collaborators":collabrator,
           "business_users":bussiness_user,
            "view_only":view_only,
            "price":price,
            "start_date":start_date,
            "end_date":end_date,
            "status":"active"
            }
            try:
                await init_dynamic_dbcreate(
        db_url=DATABASE_URL,
        tables_to_skip=["users", "subscription_plans"]
    )

               
                

                subscription = await add_subscription(
    db=db,
    company_id=company_id,
    plan_id=plan_id,
    collaborators=collabrator,
    business_users=bussiness_user,
    view_only=view_only,
    price=price,
    start_date=start_date,
    end_date=end_date,  # or some date if you want
    status="active"
)
                await db.commit()
                await db.refresh(new_company)
               
                return {
                    "company": new_company,
                    "users": company_info.users
                }
            except Exception as e:
                print(e)
                await db.rollback()
                db.expunge_all()  
               
                # Handle errors, maybe delete company DB if needed
                if db_name:
                    await delete_company_database(db_name)
                raise e


           
        
        except HTTPException as e:
            print(e)
            await db.rollback()
            db.expunge_all()  
            #re-raise HTTPException as-is it
            raise e


   
    @staticmethod
    async def update_company_data(
        company_id: str, 
        update_data: dict, 
        validated_users: List[CompanyUserCreate], 
        db: AsyncSession
    ):
        try:
            print("Starting company update for ID:", company_id)
            print("Update data received:", update_data)
            print("Validated users:", validated_users)

            # Fetch company
            stmt = select(Company).where(Company.id == company_id)
            result = await db.execute(stmt)
            company = result.scalars().first()

            if not company:
                raise HTTPException(status_code=404, detail="Company not found.")

            # Unique constraint checks
            if update_data.get("company_email") and update_data["company_email"] != company.email:
                stmt = select(Company).where(Company.email == update_data["company_email"])
                res = await db.execute(stmt)
                if res.scalars().first():
                    raise HTTPException(status_code=400, detail="Email already in use.")

            if update_data.get("company_name") and update_data["company_name"] != company.company_name:
                stmt = select(Company).where(Company.company_name == update_data["company_name"])
                res = await db.execute(stmt)
                if res.scalars().first():
                    raise HTTPException(status_code=400, detail="Company name already in use.")

            if update_data.get("company_phone_number") and update_data["company_phone_number"] != company.phone_number:
                stmt = select(Company).where(Company.phone_number == update_data["company_phone_number"])
                res = await db.execute(stmt)
                if res.scalars().first():
                    raise HTTPException(status_code=400, detail="Phone number already in use.")

            # Update company fields
            for key, value in update_data.items():
                if value is not None and hasattr(company, key):
                    print(f"Updating company field '{key}' to '{value}'")
                    setattr(company, key, value)

            # await db.commit()
            # await db.refresh(company)

            created_users = []
            print("Processing user updates...")
            print("User model class:", User)
            print("User model type:", type(User))
            print("User model table columns:", [col.key for col in User.__table__.columns])

            # Delete existing users linked to this company if new users provided
            if validated_users:
                
                stmt = delete(User).where(User.company_id == company_id)
                print("Delete statement:", stmt)
                await db.execute(stmt)
                await db.commit()
                print("Deleted")
                print(f"Deleted existing users for company {company_id}")
            
            # Add new users
            for user in validated_users:
                print("Creating user with data:", user)

                user_data = user.dict() if hasattr(user, "dict") else user
                system_generated_password = generate_password()
                print("before")

                new_user = User(
                    full_name=user_data["full_name"],
                    email=user_data["user_email"],
                    department=user_data["user_department"],
                    role=user_data["user_role"],
                    hashed_password=pwd_context.hash(system_generated_password),
                    company_name=company.company_name,
                    company_id=company.id
                )

                db.add(new_user)
                created_users.append(new_user)

                print(f"Sending email to: {user_data['user_email']} (type: {type(user_data['user_email'])})")
                try:
                    transporter.connect()
                    transporter.send(
                        user_data["user_email"],
                        "Updated account credentials",
                        f"Role: {user_data['user_role']}, Password: {system_generated_password}"
                    )
                    transporter.close()
                    print("Email sent to", user_data["user_email"])
                except Exception as email_error:
                    print(f"Failed to send email to {user_data['user_email']}: {email_error}")
            company.users_count = len(validated_users)
            await db.commit()
            await db.refresh(company)

            # Refresh created users from db (optional)
            for u in created_users:
                await db.refresh(u)

            # Update subscription if needed
            if update_data.get("plan_id") and update_data.get("billing_cycle"):
                start_date = datetime.today().date()
                end_date = CompaniesManagement.calculate_end_date(start_date, update_data["billing_cycle"])
                update_dict = {
                    "company_id": company.id,
                    "plan_id": update_data.get("plan_id"),
                    "collaborators": update_data.get("collabrator"),
                    "business_users": update_data.get("bussiness_user"),
                    "view_only": update_data.get("view_only"),
                    "price": update_data.get("price"),
                    "subscription_id": update_data.get("subscription_id"),
                    "start_date": start_date,
                    "end_date": end_date,
                    "status": "active"
                }
                print("Updating subscription with:", update_dict)
                await upsert_subscription(db, update_data=update_dict)
                print("Subscription update done.")

            print("Company update completed successfully.")
            return {
                "message": "Company updated successfully",
                "company": {
                    "id": company.id,
                    "company_name": company.company_name,
                    "email": company.email,
                    "phone_number": company.phone_number
                },
                "users": [
                    {
                        "full_name": u.full_name,
                        "email": u.email,
                        "role": u.role,
                        "department": u.department
                    } for u in created_users
                ]
            }

        except HTTPException as e:
            print("HTTPException:", e.detail)
            raise e
        except Exception as e:
            print("Exception during update_company_data:", str(e))
            await db.rollback()
            raise HTTPException(status_code=500, detail=str(e))

    

    @staticmethod
    async def get_companies(page: int, limit: int, db: AsyncSession):
        offset = (page - 1) * limit
        today = date.today()

        # 1. Get companies for the current page
        stmt = select(Company).order_by(desc(Company.created_at)).offset(offset).limit(limit)
        result = await db.execute(stmt)
        companies = result.scalars().all()

        # 2. Get total companies count
        count_stmt = select(func.count()).select_from(Company)
        count_result = await db.execute(count_stmt)
        total_companies = count_result.scalar()

        # 3. Fetch all subscriptions for the companies on this page
        company_ids = [company.id for company in companies]

        if not company_ids:
            return {
                "page": page,
                "limit": limit,
                "companies_on_page": 0,
                "total_companies": total_companies,
                "next_page": False,
                "companies": []
            }
        # 3. Get users for these companies
        company_ids = [company.id for company in companies]
        user_stmt = select(User).where(User.company_id.in_(company_ids))
        user_result = await db.execute(user_stmt)
        users = user_result.scalars().all()

        # Group users by company_id
        users_by_company = defaultdict(list)
        for user in users:
            users_by_company[user.company_id].append(user)


        from sqlalchemy.orm import selectinload

        sub_stmt = (
            select(Subscription)
            .options(selectinload(Subscription.plan))  # Replace 'plan' with actual relationship name if needed
            .where(Subscription.company_id.in_(company_ids))
        )
        sub_result = await db.execute(sub_stmt)
        subscriptions = sub_result.scalars().all()

        # 4. Group subscriptions by company_id and pick latest subscription
        subs_by_company = {}
        for sub in subscriptions:
            is_active = sub.start_date <= today <= sub.end_date
            sub_data = {
                "id": sub.subscription_id,
                "plan_name": sub.plan,
                "start_date": sub.start_date,
                "end_date": sub.end_date,
                "is_active": is_active
            }

            if sub.company_id not in subs_by_company:
                subs_by_company[sub.company_id] = sub_data
            else:
                # Pick the latest subscription by start_date
                if sub.start_date > subs_by_company[sub.company_id]["start_date"]:
                    subs_by_company[sub.company_id] = sub_data

        # 5. Prepare combined response
        companies_with_subscriptions = []
        for company in companies:
            companies_with_subscriptions.append({
                "company": company,
                "users": users_by_company.get(company.id, []),  # empty list if no users,
                "subscription": subs_by_company.get(company.id)  # None if no subscription
            })

        # 6. Return paginated companies with subscriptions
        return {
            "page": page,
            "limit": limit,
            "companies_on_page": len(companies),
            "total_companies": total_companies,
            "next_page": (offset + len(companies)) < total_companies,
            "companies": companies_with_subscriptions
        }

    @staticmethod
    async def get_company_users(company_id:str,db:AsyncSession):

        stmt = select(
        User.id,
        User.full_name,
        User.email,
        User.role,
        User.department,
        User.company_id,
        User.company_name,
        User.is_active,
        User.is_2FA_enabled,
        User.is_2FA_required,
        User.system_password_reset,
        User.created_at,
        ).where(User.company_id == company_id)

        result = await db.execute(stmt)

        users = result.mappings().all()


        return users
    
    @staticmethod
    async def get_company_details(company_id:str,db:AsyncSession):

        company =  await CompaniesManagement.get_company_by_id(company_id=company_id,db=db)
        company_users = await CompaniesManagement.get_company_users(company_id=company_id,db=db)
        subscription=await get_subscription_by_company_id(db,company_id)
        return {"company_info":company,
                "company_users":company_users,
                "subscription":subscription}
    @staticmethod
    async def activate_company(company_id:str,db:AsyncSession):
        company =  await CompaniesManagement.get_company_by_id(company_id=company_id,db=db)

        if not company.is_active:
            company.is_active = True
            await db.commit()
            await db.refresh(company)
            return {
                "message":"company status changed to active",
                "company_name": company.company_name,
                "compmay_status":company.is_active
                }
        else:
            return {
                "message":"company status already in active",
                "company_name": company.company_name,
                "compmay_status":company.is_active
                }
        
    
    @staticmethod
    async def deactivate_company(company_id:str,db:AsyncSession):
        company =  await CompaniesManagement.get_company_by_id(company_id=company_id,db=db)

        if company.is_active:
            company.is_active = False
            await db.commit()
            await db.refresh(company)
            return {
                "message":"company status changed to deactivate",
                "company_name": company.company_name,
                "company_status":company.is_active
                }
        else:
            return {
                "message":"company status already in deactivate",
                "company_name": company.company_name,
                "company_status":company.is_active
                }
        
    @staticmethod
    async def company_search(search_query:str,page:int,limit:int,db:AsyncSession):

        offset = (page - 1) * limit

        stmt = select(Company).where(
        or_(
            Company.company_name.ilike(f"%{search_query}%"),
            Company.legal_name.ilike(f"%{search_query}%"),
            Company.email.ilike(f"%{search_query}%"),
        )
        ).offset(offset).limit(limit)

        result = await db.execute(stmt)
        companies = result.scalars().all()

        return {
            "page": page,
            "page_size": limit,
            "count":len(companies),
            "results": companies
        }
    
    @staticmethod
    async def reset_company_admin_password(company_id:str,admin_id:str,db:AsyncSession):
        
        user = await CompaniesManagement.get_companyuser_by_id(user_id= admin_id,db = db)

        if(user.role != CompanyUserRoleEnum.ADMIN.value or user.department != DepartmentEnum.IT.value):

            raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail="message:you can reset only IT admin Password"
                )
        if(company_id != user.company_id):
            raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail="company Id mismatch with user company Id"
                )
        new_password = generate_password()
        user.hashed_password = pwd_context.hash(new_password)
        user.system_password_reset = True 
        user.password_reset_token = None

        await db.commit()

        return {
                "message": "Password reset successfully",
                "new_password":new_password,
                "user_email":user.email
                }

    @staticmethod
    async def company_user_activate_deactivate(company_id:str,user_id:str,db:AsyncSession):
        
        user = await CompaniesManagement.get_companyuser_by_id(user_id= user_id,db = db)

        if(company_id != user.company_id):
            raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail="company Id mismatch with user company Id"
                )
        if(user.is_active):
            message ="user is deactivated"
            user.is_active = False
        else:
            message ="user is activated"
            user.is_active = True

                
        await db.commit()
        await db.refresh(user)

        return {
                "message": message,
                "user_name":user.full_name,
                "user_email":user.email,
                "user_status":user.is_active
                
                }


    
      
