from typing import Any, Optional
from sqlalchemy import text
from app.db.session import SessionLocal

class ConfigService:
    @staticmethod
    async def get_setting(
        key: str, 
        org_id: Optional[int] = None, 
        region_code: Optional[str] = None, 
        tier_id: Optional[int] = None,
        default: Any = None
    ) -> Any:
        query = text("""
            SELECT value_json 
            FROM data.system_settings 
            WHERE key_name = :key 
            AND (
                (org_id = :org_id) OR
                (org_id IS NULL AND tier_id = :tier_id) OR
                (org_id IS NULL AND tier_id IS NULL AND region_code = :region_code) OR
                (org_id IS NULL AND tier_id IS NULL AND region_code IS NULL)
            )
            ORDER BY 
                (org_id IS NOT NULL) DESC, 
                (tier_id IS NOT NULL) DESC, 
                (region_code IS NOT NULL) DESC
            LIMIT 1
        """)
        
        async with SessionLocal() as db:
            result = await db.execute(query, {
                "key": key,
                "org_id": org_id,
                "tier_id": tier_id,
                "region_code": region_code
            })
            row = result.fetchone()
            return row[0] if row else default

config = ConfigService()
