from typing import Optional

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

from app.models.staff.staff_model import Staff, StaffStore
from app.models.staff.store_model import Store
from app.schemas.staff.staff_auth_schemas import (
    StaffRegisterBaseModel,
    StaffLoginBaseModel,
)
from passlib.context import CryptContext

from app.enums.enums import RoleTypeEnum
from app.utils.jwt import create_access_token, create_refresh_token


class StaffAuthService:
    def __init__(self, db: AsyncSession):
        self.db = db

    pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

    @staticmethod
    def get_password_hash(password: str) -> str:
        return StaffAuthService.pwd_context.hash(password)

    @staticmethod
    def verify_password(plain_password: str, hashed_password: str) -> bool:
        return StaffAuthService.pwd_context.verify(plain_password, hashed_password)

    async def login_staff(self, login_request: StaffLoginBaseModel):
        """
        Login for EMPLOYEE and MANAGER only (mobile app).
        Admins cannot login through this endpoint.
        """
        # Build query based on which field is provided
        conditions = []
        
        if login_request.username:
            from sqlalchemy import func
            conditions.append(func.lower(Staff.username) == func.lower(login_request.username))
        if login_request.email:
            conditions.append(Staff.email == login_request.email)
        
        # Use OR condition if both are provided, otherwise use the single condition
        if len(conditions) == 1:
            stmt = select(Staff).where(conditions[0])
        else:
            from sqlalchemy import or_
            stmt = select(Staff).where(or_(*conditions))
        
        result = await self.db.execute(stmt)
        staff = result.scalar_one_or_none()
        if not staff:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Incorrect username/email or staff not found",
            )
        
        # Block ADMIN and SUPERADMIN from using staff login (mobile app only for EMPLOYEE and MANAGER)
        if staff.role_type == RoleTypeEnum.ADMIN or staff.role_type == RoleTypeEnum.SUPERADMIN:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Admins cannot login through this endpoint. Please use the admin login endpoint.",
            )
        
        if not StaffAuthService.verify_password(
            login_request.password, staff.hashed_password
        ):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Incorrect password",
            )

        return {
            "message": "success",
            "status": True,
            "user": {
                "id": staff.id,
                "username": staff.username,
                "email": staff.email,
                "role_type": staff.role_type,
                "chain_id": staff.chain_id,
                "full_name": staff.full_name,
                "phone_number": staff.phone_number,
                "profile_image": staff.profile_image
            },
            "access_token": create_access_token(
                {
                    "sub": str(staff.id),  # JWT standard: sub should be string
                    "role_type": staff.role_type,
                    "chain_id": staff.chain_id,
                }
            ),
            "refresh_access_token": create_refresh_token(
                {
                    "sub": str(staff.id),  # JWT standard: sub should be string
                    "role_type": staff.role_type,
                    "chain_id": staff.chain_id,
                }
            ),
        }

    async def login_admin(self, login_request: StaffLoginBaseModel):
        """
        Login for ADMIN and SUPERADMIN (web/admin panel).
        Only ADMIN and SUPERADMIN roles can login through this endpoint.
        """
        # Build query based on which field is provided
        conditions = []
        
        if login_request.username:
            from sqlalchemy import func
            conditions.append(func.lower(Staff.username) == func.lower(login_request.username))
        if login_request.email:
            conditions.append(Staff.email == login_request.email)
        
        # Use OR condition if both are provided, otherwise use the single condition
        if len(conditions) == 1:
            stmt = select(Staff).where(conditions[0])
        else:
            from sqlalchemy import or_
            stmt = select(Staff).where(or_(*conditions))
        
        result = await self.db.execute(stmt)
        staff = result.scalar_one_or_none()
        if not staff:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Incorrect username/email or admin not found",
            )
        
        # Only allow ADMIN and SUPERADMIN roles to login through this endpoint
        if staff.role_type != RoleTypeEnum.ADMIN and staff.role_type != RoleTypeEnum.SUPERADMIN:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Only admins and superadmins can login through this endpoint. Employees and managers should use the staff login endpoint.",
            )
        
        if not StaffAuthService.verify_password(
            login_request.password, staff.hashed_password
        ):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Incorrect password",
            )

        return {
            "message": "success",
            "status": True,
            "user": {
                "id": staff.id,
                "username": staff.username,
                "email": staff.email,
                "role_type": staff.role_type,
                "chain_id": staff.chain_id,
                "full_name": staff.full_name,
                "phone_number": staff.phone_number,
                "profile_image": staff.profile_image
            },
            "access_token": create_access_token(
                {
                    "sub": str(staff.id),  # JWT standard: sub should be string
                    "role_type": staff.role_type,
                    "chain_id": staff.chain_id,
                }
            ),
            "refresh_access_token": create_refresh_token(
                {
                    "sub": str(staff.id),  # JWT standard: sub should be string
                    "role_type": staff.role_type,
                    "chain_id": staff.chain_id,
                }
            ),
        }

    async def register_staff(self, register_request: StaffRegisterBaseModel, chain_id: Optional[int]):
        """Register a new staff member."""
        # Check if email or username already exists (single query for better performance)
        existing_staff_stmt = select(Staff).where(
            or_(
                Staff.email == register_request.email,
                func.lower(Staff.username) == func.lower(register_request.username)
            )
        )
        existing_staff_result = await self.db.execute(existing_staff_stmt)
        existing_staff = existing_staff_result.scalar_one_or_none() 

        if existing_staff:
            # Determine which field caused the conflict for a more specific error message
            if existing_staff.email == register_request.email:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=f"Staff with email {register_request.email} already exists.",
                )
            elif existing_staff.username.lower() == register_request.username.lower():
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=f"Staff with username {register_request.username} already exists.",
                )

        if register_request.user_type == RoleTypeEnum.SUPERADMIN:
            superadmin_stmt = select(Staff).where(Staff.role_type == RoleTypeEnum.SUPERADMIN)
            superadmin_result = await self.db.execute(superadmin_stmt)
            if superadmin_result.scalar_one_or_none():
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="A superadmin already exists."
                )
            resolved_chain_id = None
        else:
            if chain_id is None:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="chain_id is required for non-superadmin staff."
                )
            resolved_chain_id = chain_id

        hashed_password = self.get_password_hash(register_request.password)

        new_staff = Staff(
            email=register_request.email,
            hashed_password=hashed_password,
            username=register_request.username,
            role_type=register_request.user_type,
            chain_id=resolved_chain_id,
            full_name=register_request.full_name,
            phone_number=register_request.phone_number,
            profile_image=register_request.profile_image,
        )

        self.db.add(new_staff)
        await self.db.commit()
        await self.db.refresh(new_staff)

        return {
            "message": "Registered successfully.",
            "staff": new_staff,
            "status": True,
        }

    async def assign_staff_to_store(self, staff_id: int, store_id: int):
        # Check staff id exist if yes then proceed otherwise exception
        staff_stmt = select(Staff).where(Staff.id == staff_id)
        staff_result = await self.db.execute(staff_stmt)
        staff = staff_result.scalar_one_or_none()
        
        if not staff:
            raise HTTPException(
                status_code=404, detail=f"The staff {staff_id} does not exist."
            )

        # Check store id exist if yes then proceed otherwise exception
        store_stmt = select(Store).where(Store.store_id == store_id)
        store_result = await self.db.execute(store_stmt)
        store = store_result.scalar_one_or_none()
        
        if not store:
            raise HTTPException(
                status_code=404, detail=f"The store {store_id} does not exist."
            )

        # Role-based validation: Employees can only be assigned to one store
        if staff.role_type == "EMPLOYEE":
            # Check if employee is already assigned to any store
            employee_store_stmt = select(StaffStore).where(StaffStore.staff_id == staff_id)
            employee_store_result = await self.db.execute(employee_store_stmt)
            existing_employee_store = employee_store_result.scalar_one_or_none()
            
            if existing_employee_store:
                raise HTTPException(
                    status_code=400, 
                    detail=f"Employee {staff_id} can only be assigned to one store. Employee is already assigned to store {existing_employee_store.store_id}."
                )
        else:
            # For MANAGER/ADMIN: Check if already assigned to this specific store (to prevent duplicates)
            stmt = select(StaffStore).where(
                StaffStore.staff_id == staff_id, StaffStore.store_id == store_id
            )
            result = await self.db.execute(stmt)
            existing_staff_store = result.scalar_one_or_none()
            if existing_staff_store:
                raise HTTPException(
                    status_code=400, detail=f"The staff {staff_id} is already assigned to store {store_id}."
                )

        # For MANAGER/ADMIN roles, allow multiple store assignments
        # Create the assignment
        new_link = StaffStore(
            staff_id=staff_id,
            store_id=store_id,
        )
        self.db.add(new_link)
        await self.db.commit()
        await self.db.refresh(new_link)

        return {"message": "Staff assigned to store successfully", "link": new_link}

    async def get_my_assigned_stores(self, staff_id: int):
        """Get stores assigned to the current staff member with staff details"""
        # Get staff details
        staff_stmt = select(Staff).where(Staff.id == staff_id)
        staff_result = await self.db.execute(staff_stmt)
        staff = staff_result.scalar_one_or_none()
        
        if not staff:
            raise HTTPException(
                status_code=404, detail=f"Staff {staff_id} not found."
            )

        # For ADMIN users, return all stores in their chain with all staff assigned to each store
        if staff.role_type == "ADMIN":
            stmt = select(Store).where(Store.chain_id == staff.chain_id)
            result = await self.db.execute(stmt)
            stores = result.scalars().all()
            
            assigned_stores = []
            for store in stores:
                # Get all staff assigned to this store
                staff_stmt = select(StaffStore, Staff).join(
                    Staff, StaffStore.staff_id == Staff.id
                ).where(
                    and_(
                        StaffStore.store_id == store.store_id,
                        Staff.is_deleted == False
                    )
                )
                
                staff_result = await self.db.execute(staff_stmt)
                staff_assignments = staff_result.all()
                
                store_staff = []
                for staff_store, staff_member in staff_assignments:
                    store_staff.append({
                        "staff_id": staff_member.id,
                        "username": staff_member.username,
                        "email": staff_member.email,
                        "full_name": staff_member.full_name,
                        "phone_number": staff_member.phone_number,
                        "profile_image": staff_member.profile_image,
                        "role_type": staff_member.role_type,
                        "assigned_at": staff_store.assigned_at
                    })
                
                assigned_stores.append({
                    "store_id": store.store_id,
                    "store_name": store.store_name,
                    "store_location": store.store_location,
                    "store_operational_hours": store.store_operational_hours,
                    "assigned_at": None,  # ADMIN has access to all stores, not assigned
                    "chain_id": store.chain_id,
                    "staff": store_staff
                })
        else:
            # For EMPLOYEE and MANAGER, return only assigned stores with all staff for those stores
            stmt = select(StaffStore, Store).join(
                Store, StaffStore.store_id == Store.store_id
            ).where(StaffStore.staff_id == staff_id)
            
            result = await self.db.execute(stmt)
            store_assignments = result.all()
            
            assigned_stores = []
            for staff_store, store in store_assignments:
                # Get all staff assigned to this store
                staff_stmt = select(StaffStore, Staff).join(
                    Staff, StaffStore.staff_id == Staff.id
                ).where(
                    and_(
                        StaffStore.store_id == store.store_id,
                        Staff.is_deleted == False
                    )
                )
                
                staff_result = await self.db.execute(staff_stmt)
                staff_assignments = staff_result.all()
                
                store_staff = []
                for staff_store_link, staff_member in staff_assignments:
                    store_staff.append({
                        "staff_id": staff_member.id,
                        "username": staff_member.username,
                        "email": staff_member.email,
                        "full_name": staff_member.full_name,
                        "phone_number": staff_member.phone_number,
                        "profile_image": staff_member.profile_image,
                        "role_type": staff_member.role_type,
                        "assigned_at": staff_store_link.assigned_at
                    })
                
                assigned_stores.append({
                    "store_id": store.store_id,
                    "store_name": store.store_name,
                    "store_location": store.store_location,
                    "store_operational_hours": store.store_operational_hours,
                    "assigned_at": staff_store.assigned_at,
                    "chain_id": store.chain_id,
                    "staff": store_staff
                })
        
        return {
            "message": "Stores retrieved successfully",
            "staff_info": {
                "staff_id": staff_id,
                "username": staff.username,
                "email": staff.email,
                "full_name": staff.full_name,
                "phone_number": staff.phone_number,
                "profile_image": staff.profile_image,
                "role_type": staff.role_type,
                "chain_id": staff.chain_id
            },
            "total_stores": len(assigned_stores),
            "assigned_stores": assigned_stores
        }

    async def get_all_staff(self, chain_id: int, skip: int = 0, limit: int = 100):
        """Get all staff members for a chain (Admin only)"""
        stmt = select(Staff).where(
            and_(Staff.chain_id == chain_id, Staff.is_deleted == False)
        ).offset(skip).limit(limit).order_by(Staff.created_at.desc())
        result = await self.db.execute(stmt)
        staff_list = result.scalars().all()
        
        staff_with_stores = []
        for staff in staff_list:
            # Get assigned stores with full store details for each staff
            from sqlalchemy.orm import selectinload
            store_stmt = select(StaffStore, Store).join(
                Store, StaffStore.store_id == Store.store_id
            ).where(StaffStore.staff_id == staff.id)
            store_result = await self.db.execute(store_stmt)
            store_assignments = store_result.all()
            
            assigned_stores = []
            for staff_store, store in store_assignments:
                assigned_stores.append({
                    "store_id": store.store_id,
                    "store_name": store.store_name,
                    "store_location": store.store_location,
                    "store_operational_hours": store.store_operational_hours,
                    "chain_id": store.chain_id
                })
            
            staff_with_stores.append({
                "id": staff.id,
                "username": staff.username,
                "email": staff.email,
                "role_type": staff.role_type,
                "chain_id": staff.chain_id,
                "full_name": staff.full_name,
                "phone_number": staff.phone_number,
                "profile_image": staff.profile_image,
                "assigned_stores": assigned_stores,
                "created_at": staff.created_at,
                "updated_at": staff.updated_at
            })
        
        return staff_with_stores

    async def unassign_staff_from_store(self, staff_id: int, store_id: int):
        """Unassign a store from a staff member"""
        # Check staff exists
        staff_stmt = select(Staff).where(Staff.id == staff_id)
        staff_result = await self.db.execute(staff_stmt)
        staff = staff_result.scalar_one_or_none()
        
        if not staff:
            raise HTTPException(
                status_code=404, detail=f"Staff {staff_id} not found."
            )
        
        # Check store exists
        store_stmt = select(Store).where(Store.store_id == store_id)
        store_result = await self.db.execute(store_stmt)
        store = store_result.scalar_one_or_none()
        
        if not store:
            raise HTTPException(
                status_code=404, detail=f"Store {store_id} not found."
            )
        
        # Find the assignment
        stmt = select(StaffStore).where(
            StaffStore.staff_id == staff_id,
            StaffStore.store_id == store_id
        )
        result = await self.db.execute(stmt)
        staff_store = result.scalar_one_or_none()
        
        if not staff_store:
            raise HTTPException(
                status_code=404,
                detail=f"Staff {staff_id} is not assigned to store {store_id}."
            )
        
        # Delete the assignment
        from sqlalchemy import delete
        delete_stmt = delete(StaffStore).where(
            StaffStore.staff_id == staff_id,
            StaffStore.store_id == store_id
        )
        await self.db.execute(delete_stmt)
        await self.db.commit()
        
        return {"message": f"Staff {staff_id} unassigned from store {store_id} successfully"}

    async def update_staff(self, staff_id: int, update_data: dict):
        """Update staff details"""
        stmt = select(Staff).where(Staff.id == staff_id)
        result = await self.db.execute(stmt)
        staff = result.scalar_one_or_none()
        
        if not staff:
            raise HTTPException(
                status_code=404, detail=f"Staff {staff_id} not found."
            )
        
        # Update fields
        for field, value in update_data.items():
            if value is not None and hasattr(staff, field):
                setattr(staff, field, value)
        
        await self.db.commit()
        await self.db.refresh(staff)
        
        return staff

    async def change_staff_password(self, staff_id: int, new_password: str):
        """Change staff password"""
        stmt = select(Staff).where(Staff.id == staff_id)
        result = await self.db.execute(stmt)
        staff = result.scalar_one_or_none()
        
        if not staff:
            raise HTTPException(
                status_code=404, detail=f"Staff {staff_id} not found."
            )
        
        # Hash and update password
        hashed_password = self.get_password_hash(new_password)
        staff.hashed_password = hashed_password
        
        await self.db.commit()
        await self.db.refresh(staff)
        
        return {"message": f"Password changed successfully for staff {staff_id}"}

    async def get_all_admins_with_chain(self, skip: int = 0, limit: int = 100):
        """Get all admins with their chain information (Superadmin only)"""
        from sqlalchemy import func
        from app.models.staff.store_model import Chain
        
        # Get total count of admins (excluding soft-deleted)
        count_stmt = select(func.count(Staff.id)).where(
            and_(
                Staff.role_type == RoleTypeEnum.ADMIN,
                Staff.is_deleted == False
            )
        )
        count_result = await self.db.execute(count_stmt)
        total = count_result.scalar_one()
        
        # Query all admins (excluding superadmin and soft-deleted)
        stmt = (
            select(Staff)
            .where(
                and_(
                    Staff.role_type == RoleTypeEnum.ADMIN,
                    Staff.is_deleted == False
                )
            )
            .offset(skip)
            .limit(limit)
            .order_by(Staff.created_at.desc())
        )
        result = await self.db.execute(stmt)
        admin_list = result.scalars().all()
        
        # Get all unique chain_ids from admins
        chain_ids = {admin.chain_id for admin in admin_list if admin.chain_id}
        
        # Fetch all chains in one query
        chains_dict = {}
        if chain_ids:
            chain_stmt = select(Chain).where(
                and_(
                    Chain.chain_id.in_(chain_ids),
                    Chain.is_deleted == False
                )
            )
            chain_result = await self.db.execute(chain_stmt)
            chains = chain_result.scalars().all()
            chains_dict = {chain.chain_id: chain for chain in chains}
        
        # Build response with chain information
        admins_with_chain = []
        for admin in admin_list:
            chain_info = None
            if admin.chain_id and admin.chain_id in chains_dict:
                chain = chains_dict[admin.chain_id]
                chain_info = {
                    "chain_id": chain.chain_id,
                    "chain_name": chain.chain_name,
                    "chain_code": chain.chain_code
                }
            
            admins_with_chain.append({
                "id": admin.id,
                "username": admin.username,
                "email": admin.email,
                "role_type": admin.role_type,
                "chain_id": admin.chain_id,
                "full_name": admin.full_name,
                "phone_number": admin.phone_number,
                "profile_image": admin.profile_image,
                "chain": chain_info,
                "created_at": admin.created_at,
                "updated_at": admin.updated_at
            })
        
        return {
            "admins": admins_with_chain,
            "total": total
        }

    async def delete_staff(self, staff_id: int, chain_id: int) -> bool:
        """
        Soft delete a staff member (Admin only).
        
        Cannot delete if:
        - Staff has active product listings (as employee, manager, or staff)
        - Staff has manager discount records
        
        Store assignments will be automatically removed.
        Admin can only delete staff in their chain.
        """
        from datetime import datetime, timezone
        from app.models.listing.products import ProductListing, ManagerDiscount
        from sqlalchemy import delete
        
        # Verify staff exists and belongs to admin's chain
        stmt = select(Staff).where(
            and_(
                Staff.id == staff_id,
                Staff.chain_id == chain_id,
                Staff.is_deleted == False
            )
        )
        result = await self.db.execute(stmt)
        staff = result.scalar_one_or_none()
        
        if not staff:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Staff not found, already deleted, or does not belong to your chain"
            )
        
        # Prevent deleting superadmin
        if staff.role_type == RoleTypeEnum.SUPERADMIN:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Cannot delete superadmin"
            )
        
        # Check for active product listings (as employee)
        employee_listings_stmt = select(ProductListing).where(
            ProductListing.employee_id == staff_id
        )
        employee_listings_result = await self.db.execute(employee_listings_stmt)
        employee_listings = employee_listings_result.scalars().all()
        
        if employee_listings:
            listing_count = len(employee_listings)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete staff. {listing_count} product listing(s) are linked to this staff member as employee. Please reassign or delete listings first."
            )
        
        # Check for active product listings (as manager)
        manager_listings_stmt = select(ProductListing).where(
            ProductListing.manager_id == staff_id
        )
        manager_listings_result = await self.db.execute(manager_listings_stmt)
        manager_listings = manager_listings_result.scalars().all()
        
        if manager_listings:
            listing_count = len(manager_listings)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete staff. {listing_count} product listing(s) are linked to this staff member as manager. Please reassign or delete listings first."
            )
        
        # Check for active product listings (as staff who initiated)
        staff_listings_stmt = select(ProductListing).where(
            ProductListing.staff_id == staff_id
        )
        staff_listings_result = await self.db.execute(staff_listings_stmt)
        staff_listings = staff_listings_result.scalars().all()
        
        if staff_listings:
            listing_count = len(staff_listings)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete staff. {listing_count} product listing(s) are linked to this staff member. Please reassign or delete listings first."
            )
        
        # Check for manager discount records
        discounts_stmt = select(ManagerDiscount).where(
            ManagerDiscount.manager_id == staff_id
        )
        discounts_result = await self.db.execute(discounts_stmt)
        discounts = discounts_result.scalars().all()
        
        if discounts:
            discount_count = len(discounts)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete staff. {discount_count} manager discount record(s) are linked to this staff member. Please delete discount records first."
            )
        
        # Remove store assignments
        delete_assignments_stmt = delete(StaffStore).where(
            StaffStore.staff_id == staff_id
        )
        await self.db.execute(delete_assignments_stmt)
        
        # Soft delete the staff member
        staff.is_deleted = True
        staff.deleted_at = datetime.now(timezone.utc)
        await self.db.commit()
        
        return True
    
    async def delete_admin_by_superadmin(self, admin_id: int) -> bool:
        """
        Soft delete an admin by superadmin (can delete admins from any chain).
        
        Cannot delete if:
        - Admin has active product listings (as employee, manager, or staff)
        - Admin has manager discount records
        
        Store assignments will be automatically removed.
        Superadmin can delete admins from any chain.
        """
        from datetime import datetime, timezone
        from app.models.listing.products import ProductListing, ManagerDiscount
        from sqlalchemy import delete
        
        # Verify admin exists and is not already deleted
        stmt = select(Staff).where(
            and_(
                Staff.id == admin_id,
                Staff.is_deleted == False
            )
        )
        result = await self.db.execute(stmt)
        admin = result.scalar_one_or_none()
        
        if not admin:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Admin not found or already deleted"
            )
        
        # Verify it's actually an admin
        if admin.role_type != RoleTypeEnum.ADMIN:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Staff member with ID {admin_id} is not an admin (role: {admin.role_type})"
            )
        
        # Prevent deleting superadmin (extra safety check)
        if admin.role_type == RoleTypeEnum.SUPERADMIN:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Cannot delete superadmin"
            )
        
        # Check for active product listings (as employee)
        employee_listings_stmt = select(ProductListing).where(
            ProductListing.employee_id == admin_id
        )
        employee_listings_result = await self.db.execute(employee_listings_stmt)
        employee_listings = employee_listings_result.scalars().all()
        
        if employee_listings:
            listing_count = len(employee_listings)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete admin. {listing_count} product listing(s) are linked to this admin as employee. Please reassign or delete listings first."
            )
        
        # Check for active product listings (as manager)
        manager_listings_stmt = select(ProductListing).where(
            ProductListing.manager_id == admin_id
        )
        manager_listings_result = await self.db.execute(manager_listings_stmt)
        manager_listings = manager_listings_result.scalars().all()
        
        if manager_listings:
            listing_count = len(manager_listings)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete admin. {listing_count} product listing(s) are linked to this admin as manager. Please reassign or delete listings first."
            )
        
        # Check for active product listings (as staff who initiated)
        staff_listings_stmt = select(ProductListing).where(
            ProductListing.staff_id == admin_id
        )
        staff_listings_result = await self.db.execute(staff_listings_stmt)
        staff_listings = staff_listings_result.scalars().all()
        
        if staff_listings:
            listing_count = len(staff_listings)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete admin. {listing_count} product listing(s) are linked to this admin. Please reassign or delete listings first."
            )
        
        # Check for manager discount records
        discounts_stmt = select(ManagerDiscount).where(
            ManagerDiscount.manager_id == admin_id
        )
        discounts_result = await self.db.execute(discounts_stmt)
        discounts = discounts_result.scalars().all()
        
        if discounts:
            discount_count = len(discounts)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete admin. {discount_count} manager discount record(s) are linked to this admin. Please delete discount records first."
            )
        
        # Remove store assignments
        delete_assignments_stmt = delete(StaffStore).where(
            StaffStore.staff_id == admin_id
        )
        await self.db.execute(delete_assignments_stmt)
        
        # Perform soft delete
        staff.is_deleted = True
        staff.deleted_at = datetime.now(timezone.utc)
        
        await self.db.commit()
        await self.db.refresh(staff)
        
        return True
    
    async def delete_admin_by_superadmin(self, admin_id: int) -> bool:
        """
        Soft delete an admin by superadmin (can delete admins from any chain).
        
        Cannot delete if:
        - Admin has active product listings (as employee, manager, or staff)
        - Admin has manager discount records
        
        Store assignments will be automatically removed.
        Superadmin can delete admins from any chain.
        """
        from datetime import datetime, timezone
        from app.models.listing.products import ProductListing, ManagerDiscount
        from sqlalchemy import delete
        
        # Verify admin exists and is not already deleted
        stmt = select(Staff).where(
            and_(
                Staff.id == admin_id,
                Staff.is_deleted == False
            )
        )
        result = await self.db.execute(stmt)
        admin = result.scalar_one_or_none()
        
        if not admin:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Admin not found or already deleted"
            )
        
        # Verify it's actually an admin
        if admin.role_type != RoleTypeEnum.ADMIN:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Staff member with ID {admin_id} is not an admin (role: {admin.role_type})"
            )
        
        # Check for active product listings (as employee)
        employee_listings_stmt = select(ProductListing).where(
            ProductListing.employee_id == admin_id
        )
        employee_listings_result = await self.db.execute(employee_listings_stmt)
        employee_listings = employee_listings_result.scalars().all()
        
        if employee_listings:
            listing_count = len(employee_listings)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete admin. {listing_count} product listing(s) are linked to this admin as employee. Please reassign or delete listings first."
            )
        
        # Check for active product listings (as manager)
        manager_listings_stmt = select(ProductListing).where(
            ProductListing.manager_id == admin_id
        )
        manager_listings_result = await self.db.execute(manager_listings_stmt)
        manager_listings = manager_listings_result.scalars().all()
        
        if manager_listings:
            listing_count = len(manager_listings)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete admin. {listing_count} product listing(s) are linked to this admin as manager. Please reassign or delete listings first."
            )
        
        # Check for active product listings (as staff who initiated)
        staff_listings_stmt = select(ProductListing).where(
            ProductListing.staff_id == admin_id
        )
        staff_listings_result = await self.db.execute(staff_listings_stmt)
        staff_listings = staff_listings_result.scalars().all()
        
        if staff_listings:
            listing_count = len(staff_listings)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete admin. {listing_count} product listing(s) are linked to this admin. Please reassign or delete listings first."
            )
        
        # Check for manager discount records
        discounts_stmt = select(ManagerDiscount).where(
            ManagerDiscount.manager_id == admin_id
        )
        discounts_result = await self.db.execute(discounts_stmt)
        discounts = discounts_result.scalars().all()
        
        if discounts:
            discount_count = len(discounts)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete admin. {discount_count} manager discount record(s) are linked to this admin. Please delete discount records first."
            )
        
        # Remove store assignments
        delete_assignments_stmt = delete(StaffStore).where(
            StaffStore.staff_id == admin_id
        )
        await self.db.execute(delete_assignments_stmt)
        
        # Perform soft delete
        admin.is_deleted = True
        admin.deleted_at = datetime.now(timezone.utc)
        
        await self.db.commit()
        await self.db.refresh(admin)
        
        return True