# ws_package/services/server_service.py
from typing import Optional

from ws_package.entities.s3bucket_entity import S3BucketEntity
from ws_package.repositories.server_repo import server_manager
from ws_package.services.api_request_service import APIRequest
from ws_package.log.writer import LogWriter


logger = LogWriter.file(__name__)


class ServerService:
    application_s3bucket_detail_url: Optional[str] = None
    headers: Optional[dict] = None

    async def save_s3bucket(self, s3bucket_entity: S3BucketEntity, org_id: int):
        """
        Save S3 bucket configuration (will be encrypted automatically)
        
        Note: Data is encrypted before storage via AppConfig model event handlers
        """
        is_s3bucket_saved = await server_manager.save_s3bucket(s3bucket_entity, org_id)
        if is_s3bucket_saved:
            # Get the saved config (decrypted when loaded)
            saved_config = await server_manager.get_s3bucket(org_id)
            if saved_config:
                # Extract attributes (already decrypted by repository)
                return S3BucketEntity(
                    access_key=saved_config.access_key,
                    secret_access_key=saved_config.secret_access_key,
                    region=saved_config.region,
                    bucket=saved_config.bucket,
                    session_token=getattr(saved_config, "session_token", "") or "",
                    expire_time=getattr(saved_config, "expire_time", "") or "",
                )
            # Fallback to original entity if config not found
            return s3bucket_entity

    def fetch_s3bucket_details(self, payload):
        if self.application_s3bucket_detail_url is not None and self.headers is not None:
            self.api_request = APIRequest(
                url=self.application_s3bucket_detail_url,
                headers=self.headers
            )
            self.api_request.post(payload)  # Synchronous call
            return self.api_request.data()
    
    async def get_s3bucket(self, org_id: int):
        return await server_manager.get_s3bucket(org_id=org_id)

