# [DEF:ConnectionsRouter:Module]
# @SEMANTICS: api, router, connections, database
# @PURPOSE: Defines the FastAPI router for managing external database connections.
# @LAYER: UI (API)
# @RELATION: Depends on SQLAlchemy session.
# @CONSTRAINT: Must use belief_scope for logging.

# [SECTION: IMPORTS]
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from ...core.database import get_db
from ...models.connection import ConnectionConfig
from pydantic import BaseModel
from datetime import datetime
from ...core.logger import logger, belief_scope
# [/SECTION]

router = APIRouter()

# [DEF:ConnectionSchema:Class]
# @PURPOSE: Pydantic model for connection response.
class ConnectionSchema(BaseModel):
    id: str
    name: str
    type: str
    host: Optional[str] = None
    port: Optional[int] = None
    database: Optional[str] = None
    username: Optional[str] = None
    created_at: datetime

    class Config:
        orm_mode = True
# [/DEF:ConnectionSchema:Class]

# [DEF:ConnectionCreate:Class]
# @PURPOSE: Pydantic model for creating a connection.
class ConnectionCreate(BaseModel):
    name: str
    type: str
    host: Optional[str] = None
    port: Optional[int] = None
    database: Optional[str] = None
    username: Optional[str] = None
    password: Optional[str] = None
# [/DEF:ConnectionCreate:Class]

# [DEF:list_connections:Function]
# @PURPOSE: Lists all saved connections.
# @PRE:     Database session is active.
# @POST:    Returns list of connection configs.
# @PARAM:   db (Session) - Database session.
# @RETURN:  List[ConnectionSchema] - List of connections.
@router.get("", response_model=List[ConnectionSchema])
async def list_connections(db: Session = Depends(get_db)):
    with belief_scope("ConnectionsRouter.list_connections"):
        connections = db.query(ConnectionConfig).all()
        return connections
# [/DEF:list_connections:Function]

# [DEF:create_connection:Function]
# @PURPOSE: Creates a new connection configuration.
# @PRE:     Connection name is unique.
# @POST:    Connection is saved to DB.
# @PARAM:   connection (ConnectionCreate) - Config data.
# @PARAM:   db (Session) - Database session.
# @RETURN:  ConnectionSchema - Created connection.
@router.post("", response_model=ConnectionSchema, status_code=status.HTTP_201_CREATED)
async def create_connection(connection: ConnectionCreate, db: Session = Depends(get_db)):
    with belief_scope("ConnectionsRouter.create_connection", f"name={connection.name}"):
        db_connection = ConnectionConfig(**connection.dict())
        db.add(db_connection)
        db.commit()
        db.refresh(db_connection)
        logger.info(f"[ConnectionsRouter.create_connection][Success] Created connection {db_connection.id}")
        return db_connection
# [/DEF:create_connection:Function]

# [DEF:delete_connection:Function]
# @PURPOSE: Deletes a connection configuration.
# @PRE:     Connection ID exists.
# @POST:    Connection is removed from DB.
# @PARAM:   connection_id (str) - ID to delete.
# @PARAM:   db (Session) - Database session.
# @RETURN:  None.
@router.delete("/{connection_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_connection(connection_id: str, db: Session = Depends(get_db)):
    with belief_scope("ConnectionsRouter.delete_connection", f"id={connection_id}"):
        db_connection = db.query(ConnectionConfig).filter(ConnectionConfig.id == connection_id).first()
        if not db_connection:
            logger.error(f"[ConnectionsRouter.delete_connection][State] Connection {connection_id} not found")
            raise HTTPException(status_code=404, detail="Connection not found")
        db.delete(db_connection)
        db.commit()
        logger.info(f"[ConnectionsRouter.delete_connection][Success] Deleted connection {connection_id}")
        return
# [/DEF:delete_connection:Function]

# [/DEF:ConnectionsRouter:Module]