# #region GitConfigRoutes [C:2] [TYPE Module] [SEMANTICS fastapi, git, api, search, connection]
# @BRIEF FastAPI endpoints for Git server configuration CRUD and connection testing.
# @LAYER API


from fastapi import Depends, HTTPException
from sqlalchemy.orm import Session

from src.api.routes.git_schemas import (
    GitServerConfigCreate,
    GitServerConfigSchema,
    GitServerConfigUpdate,
)
from src.core.database import get_db
from src.core.logger import belief_scope
from src.dependencies import has_permission
from src.models.git import GitServerConfig

from ._deps import get_git_service
from ._router import router


# #region get_git_configs [C:2] [TYPE Function]
# @BRIEF List all configured Git servers.
@router.get("/config", response_model=list[GitServerConfigSchema])
async def get_git_configs(
    db: Session = Depends(get_db),
    _=Depends(has_permission("git_config", "READ")),
):
    with belief_scope("get_git_configs"):
        configs = db.query(GitServerConfig).all()
        result = []
        for config in configs:
            schema = GitServerConfigSchema.from_orm(config)
            schema.pat = "********"
            result.append(schema)
        return result
# #endregion get_git_configs


# #region create_git_config [C:2] [TYPE Function]
# @BRIEF Register a new Git server configuration.
@router.post("/config", response_model=GitServerConfigSchema)
async def create_git_config(
    config: GitServerConfigCreate,
    db: Session = Depends(get_db),
    _=Depends(has_permission("admin:settings", "WRITE")),
):
    with belief_scope("create_git_config"):
        config_dict = config.dict(exclude={"config_id"})
        db_config = GitServerConfig(**config_dict)
        db.add(db_config)
        db.commit()
        db.refresh(db_config)
        return db_config
# #endregion create_git_config


# #region update_git_config [C:2] [TYPE Function]
# @BRIEF Update an existing Git server configuration.
@router.put("/config/{config_id}", response_model=GitServerConfigSchema)
async def update_git_config(
    config_id: str,
    config_update: GitServerConfigUpdate,
    db: Session = Depends(get_db),
    _=Depends(has_permission("admin:settings", "WRITE")),
):
    with belief_scope("update_git_config"):
        db_config = (
            db.query(GitServerConfig).filter(GitServerConfig.id == config_id).first()
        )
        if not db_config:
            raise HTTPException(status_code=404, detail="Configuration not found")

        update_data = config_update.dict(exclude_unset=True)
        if update_data.get("pat") == "********":
            update_data.pop("pat")

        for key, value in update_data.items():
            setattr(db_config, key, value)

        db.commit()
        db.refresh(db_config)

        result_schema = GitServerConfigSchema.from_orm(db_config)
        result_schema.pat = "********"
        return result_schema
# #endregion update_git_config


# #region delete_git_config [C:2] [TYPE Function]
# @BRIEF Remove a Git server configuration.
@router.delete("/config/{config_id}")
async def delete_git_config(
    config_id: str,
    db: Session = Depends(get_db),
    _=Depends(has_permission("admin:settings", "WRITE")),
):
    with belief_scope("delete_git_config"):
        db_config = (
            db.query(GitServerConfig).filter(GitServerConfig.id == config_id).first()
        )
        if not db_config:
            raise HTTPException(status_code=404, detail="Configuration not found")

        db.delete(db_config)
        db.commit()
        return {"status": "success", "message": "Configuration deleted"}
# #endregion delete_git_config


# #region test_git_config [C:2] [TYPE Function]
# @BRIEF Validate connection to a Git server using provided credentials.
@router.post("/config/test")
async def test_git_config(
    config: GitServerConfigCreate,
    db: Session = Depends(get_db),
    _=Depends(has_permission("git_config", "READ")),
):
    with belief_scope("test_git_config"):
        _git_service = get_git_service()
        pat_to_use = config.pat
        if pat_to_use == "********":
            if config.config_id:
                db_config = (
                    db.query(GitServerConfig)
                    .filter(GitServerConfig.id == config.config_id)
                    .first()
                )
                if db_config:
                    pat_to_use = db_config.pat
            else:
                db_config = (
                    db.query(GitServerConfig)
                    .filter(GitServerConfig.url == config.url)
                    .first()
                )
                if db_config:
                    pat_to_use = db_config.pat

        success = await _git_service.test_connection(
            config.provider, config.url, pat_to_use
        )
        if success:
            return {"status": "success", "message": "Connection successful"}
        else:
            raise HTTPException(status_code=400, detail="Connection failed")
# #endregion test_git_config
# #endregion GitConfigRoutes
