# services/tenant/app/repositories/tenant_settings_repository.py
"""
Tenant Settings Repository
Data access layer for tenant settings
"""

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from typing import Optional
from uuid import UUID
import structlog

from ..models.tenant_settings import TenantSettings

logger = structlog.get_logger()


class TenantSettingsRepository:
    """Repository for TenantSettings data access"""

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

    async def get_by_tenant_id(self, tenant_id: UUID) -> Optional[TenantSettings]:
        """
        Get tenant settings by tenant ID

        Args:
            tenant_id: UUID of the tenant

        Returns:
            TenantSettings or None if not found
        """
        result = await self.db.execute(
            select(TenantSettings).where(TenantSettings.tenant_id == tenant_id)
        )
        return result.scalar_one_or_none()

    async def create(self, settings: TenantSettings) -> TenantSettings:
        """
        Create new tenant settings

        Args:
            settings: TenantSettings instance to create

        Returns:
            Created TenantSettings instance
        """
        self.db.add(settings)
        await self.db.commit()
        await self.db.refresh(settings)
        return settings

    async def update(self, settings: TenantSettings) -> TenantSettings:
        """
        Update tenant settings

        Args:
            settings: TenantSettings instance with updates

        Returns:
            Updated TenantSettings instance
        """
        await self.db.commit()
        await self.db.refresh(settings)
        return settings

    async def delete(self, tenant_id: UUID) -> None:
        """
        Delete tenant settings

        Args:
            tenant_id: UUID of the tenant
        """
        result = await self.db.execute(
            select(TenantSettings).where(TenantSettings.tenant_id == tenant_id)
        )
        settings = result.scalar_one_or_none()

        if settings:
            await self.db.delete(settings)
            await self.db.commit()
