"""Connector repository (tenant-scoped)."""

from __future__ import annotations

import uuid

from sqlalchemy import select
from sqlalchemy.orm import Session

from legate.db.models.connector import Connector


def create(
    db: Session,
    *,
    workspace_id: uuid.UUID,
    type: str,
    name: str,
    config_json: dict | None = None,
    created_by: uuid.UUID | None = None,
) -> Connector:
    connector = Connector(
        workspace_id=workspace_id,
        type=type,
        name=name,
        config_json=config_json or {},
        created_by=created_by,
    )
    db.add(connector)
    db.flush()
    return connector


def get(db: Session, *, workspace_id: uuid.UUID, connector_id: uuid.UUID) -> Connector | None:
    return db.scalars(
        select(Connector).where(
            Connector.id == connector_id, Connector.workspace_id == workspace_id
        )
    ).first()


def list_for_workspace(db: Session, *, workspace_id: uuid.UUID) -> list[Connector]:
    return list(
        db.scalars(
            select(Connector)
            .where(Connector.workspace_id == workspace_id)
            .order_by(Connector.created_at.asc())
        ).all()
    )


def delete(db: Session, connector: Connector) -> None:
    db.delete(connector)
    db.flush()
