"""Credential repository.

Stores only envelope-encrypted material. Plaintext never touches this layer.
"""

from __future__ import annotations

import uuid

from sqlalchemy import select
from sqlalchemy.orm import Session

from legate.db.models.credential import Credential
from legate.vault import EncryptedSecret


def upsert(
    db: Session,
    *,
    workspace_id: uuid.UUID,
    connector_id: uuid.UUID,
    encrypted: EncryptedSecret,
    meta: dict | None = None,
    scopes: list[str] | None = None,
) -> Credential:
    credential = get_for_connector(db, connector_id=connector_id)
    if credential is None:
        credential = Credential(workspace_id=workspace_id, connector_id=connector_id)
        db.add(credential)
    credential.ciphertext = encrypted.ciphertext
    credential.wrapped_dek = encrypted.wrapped_dek
    credential.key_version = encrypted.key_version
    if meta is not None:
        credential.meta = meta
    if scopes is not None:
        credential.scopes = scopes
    db.flush()
    return credential


def get_for_connector(db: Session, *, connector_id: uuid.UUID) -> Credential | None:
    return db.scalars(select(Credential).where(Credential.connector_id == connector_id)).first()
