# repository/ws_org_repo.py

from ws_package.models.base import OrgConfigurations, async_session
from ws_package.entities.org_entity import OrgEntity
from ws_package.log.writer import LogWriter
import threading
from ws_package.utils.db_lock_manager import db_lock_manager
from ws_package.utils.db_write_queue import db_write_queue, WriteOperationType

logger = LogWriter.file(__name__)


class OrgManager:
    # Removed individual db_write_lock - now using centralized db_lock_manager
    
    async def save_org_record(self, org_entity: OrgEntity):
        """
        Save organization record to in-memory queue.
        The database writer thread will process this asynchronously.
        
        Returns:
            org_entity for backward compatibility
        """
        try:
            # Enqueue to in-memory queue (non-blocking, no SQLite operation)
            success = db_write_queue.enqueue(
                operation_type=WriteOperationType.ORG,
                table_name="org_configuration",  # Updated to match new table name
                data=org_entity.model_dump()
            )
            
            if success:
                logger.debug("Enqueued Org record: %s", org_entity.org_id)
                # Return entity for backward compatibility
                return org_entity
            else:
                logger.error("Failed to enqueue Org record - queue may be full")
                return False
                
        except Exception as e:
            logger.error("Error enqueueing Org record: %s", e, exc_info=True)
            return False


org_manager = OrgManager()
