"""Control-plane secret storage abstraction."""

from __future__ import annotations

import os

from sqlalchemy import select

from config.control_plane import get_control_plane_session
from platform.secrets.encryption import PlaceholderAESCipher
from platform.tenants.models import TenantSecret


class SecretsManager:
    """Encrypt and retrieve per-tenant secrets from the control plane."""

    def __init__(self, key: str | None = None) -> None:
        master_key = key or os.getenv("PLATFORM_SECRETS_KEY", "development-only-key")
        self.cipher = PlaceholderAESCipher(master_key)

    def put_secret(self, *, tenant_id: str, secret_name: str, secret_value: str, app_id: str | None = None) -> TenantSecret:
        encrypted_value = self.cipher.encrypt(secret_value)
        with get_control_plane_session() as session:
            stmt = (
                select(TenantSecret)
                .where(
                    TenantSecret.tenant_id == tenant_id,
                    TenantSecret.secret_name == secret_name,
                    TenantSecret.app_id == app_id,
                )
                .limit(1)
            )
            record = session.execute(stmt).scalar_one_or_none()
            if record is None:
                record = TenantSecret(
                    tenant_id=tenant_id,
                    app_id=app_id,
                    secret_name=secret_name,
                    secret_value_encrypted=encrypted_value,
                )
                session.add(record)
            else:
                record.secret_value_encrypted = encrypted_value
            session.commit()
            session.refresh(record)
            return record

    def get_secret(self, *, tenant_id: str, secret_name: str, app_id: str | None = None) -> str | None:
        with get_control_plane_session() as session:
            stmt = (
                select(TenantSecret)
                .where(
                    TenantSecret.tenant_id == tenant_id,
                    TenantSecret.secret_name == secret_name,
                    TenantSecret.app_id == app_id,
                )
                .limit(1)
            )
            record = session.execute(stmt).scalar_one_or_none()
            if record is None:
                return None
            return self.cipher.decrypt(record.secret_value_encrypted)

