# ws_package/services/user_service.py

from typing import Optional

from ws_package.entities.user_entity import UserEntity
from ws_package.entities.org_entity import OrgEntity
from ws_package.repositories.user_repo import user_manager
from ws_package.services.api_request_service import APIRequest


class UserService:
    def __init__(self):
        # Instance-specific state (converted from class-level)
        self.application_login_url: Optional[str] = None
        self.application_config_url: Optional[str] = None
        self.application_org_config_url: Optional[str] = None
        self.headers: Optional[dict] = None

    def authenticate_user(self, payload):
        if self.application_login_url is not None:
            api_request = APIRequest(
                url=self.application_login_url,
                headers=self.headers
            )
            api_request.post(payload)  # Synchronous call
            response_data = api_request.stealth_data()
            if response_data:
                # The API response structure shows that response_data contains the user data
                # We need to return the data and a default bucket since bucket is not in the response
                bucket = 'aws'  # Default bucket since it's not in the API response
                return response_data, bucket
            return None
        
    async def save_user(self, user_entity: UserEntity):
        is_user_saved = await user_manager.save_user(user_entity)
        if is_user_saved:
            # Extract attributes properly to avoid SQLAlchemy internal state
            return UserEntity(
                username=is_user_saved.username,
                name=is_user_saved.name,
                timezone=is_user_saved.timezone,
                token=is_user_saved.token,
                sd_token=str(is_user_saved.sd_token),
                org_id=is_user_saved.org_id,
                user_id=is_user_saved.user_id,
                bucket=is_user_saved.bucket,
                timezone_preference=getattr(is_user_saved, "timezone_preference", 1),
            )
    
    async def get_user(self, user_id: int):
        return await user_manager.get_user(user_id=user_id)

    def fetch_user_org(self, payload):
        if self.application_org_config_url is not None and self.headers is not None:
            api_request = APIRequest(
                url=self.application_org_config_url,
                headers=self.headers
            )
            api_request.post(payload)  # Synchronous call
            return api_request.data()
    
    async def save_user_org(self, org_entity: OrgEntity):
        is_org_saved = await user_manager.save_user_org(org_entity)
        if is_org_saved:
            # Extract attributes properly to avoid SQLAlchemy internal state (_sa_instance_state)
            return OrgEntity(
                org_id=is_org_saved.org_id,
                user_id=is_org_saved.user_id,
                screenshot_interval=is_org_saved.screenshot_interval,
                date=is_org_saved.date,
                appandurlstatus=is_org_saved.appandurlstatus,
                ssfrequencystatus=is_org_saved.ssfrequencystatus,
                screenshotblurstatus=is_org_saved.screenshotblurstatus,
                livescreenshotstatus=is_org_saved.livescreenshotstatus,
                idlenotes_status=is_org_saved.idlenotes_status,
                break_limit=is_org_saved.break_limit,
                break_status=is_org_saved.break_status,
                notes_char_limit=is_org_saved.notes_char_limit,
                idle_limit=is_org_saved.idle_limit,
                can_delete_scrnshots=is_org_saved.can_delete_scrnshots,
                restrict_timer_to_jobsite=is_org_saved.restrict_timer_to_jobsite,
                todos_files_upload_limit=is_org_saved.todos_files_upload_limit,
                org_timezone=is_org_saved.org_timezone,
                user_timezone=is_org_saved.user_timezone,
                user_timezone_gmt=is_org_saved.user_timezone_gmt,
                user_timezone_gmt_dst=is_org_saved.user_timezone_gmt_dst,
                user_timezone_gmt_shortcode=is_org_saved.user_timezone_gmt_shortcode,
                bulkInvite=is_org_saved.bulkInvite,
                timeInterval=is_org_saved.timeInterval,
                blur_intensity=is_org_saved.blur_intensity,
                img_quality=is_org_saved.img_quality,
                notification_status=is_org_saved.notification_status,
                weekly_limit=getattr(is_org_saved, 'weekly_limit', None),
                org_week_start_day=getattr(is_org_saved, 'org_week_start_day', None),
                worked_total_hours_week=getattr(is_org_saved, 'worked_total_hours_week', None),
                worked_total_hours_week_leaving_today=getattr(is_org_saved, 'worked_total_hours_week_leaving_today', None),
                daily_limit=getattr(is_org_saved, 'daily_limit', None),
                weekly_limit_hours=getattr(is_org_saved, 'weekly_limit_hours', None),
                worked_total_hours_today=getattr(is_org_saved, 'worked_total_hours_today', None),
                limit_action=getattr(is_org_saved, 'limit_action', None),
                timezone_preference=getattr(is_org_saved, 'timezone_preference', 1),
            )
    
    async def get_user_org(self, user_id: int):
        return await user_manager.get_user_org(user_id=user_id)
