# #region GitGiteaRoutes [C:2] [TYPE Module] [SEMANTICS fastapi, git, gitea, api]
# @BRIEF FastAPI endpoints for Gitea-specific repository operations.
# @LAYER API


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

from src.api.routes.git_schemas import (
    GiteaRepoCreateRequest,
    GiteaRepoSchema,
    RemoteRepoCreateRequest,
    RemoteRepoSchema,
)
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 GitProvider

from ._deps import get_git_service
from ._helpers import _get_git_config_or_404
from ._router import router


# #region list_gitea_repositories [C:2] [TYPE Function]
# @BRIEF List repositories in Gitea for a saved Gitea config.
@router.get("/config/{config_id}/gitea/repos", response_model=list[GiteaRepoSchema])
async def list_gitea_repositories(
    config_id: str,
    db: Session = Depends(get_db),
    _=Depends(has_permission("git_config", "READ")),
):
    _gs = get_git_service()
    with belief_scope("list_gitea_repositories"):
        config = _get_git_config_or_404(db, config_id)
        if config.provider != GitProvider.GITEA:
            raise HTTPException(
                status_code=400, detail="This endpoint supports GITEA provider only"
            )
        repos = await _gs.list_gitea_repositories(config.url, config.pat)
        return [
            GiteaRepoSchema(
                name=repo.get("name", ""),
                full_name=repo.get("full_name", ""),
                private=bool(repo.get("private", False)),
                clone_url=repo.get("clone_url"),
                html_url=repo.get("html_url"),
                ssh_url=repo.get("ssh_url"),
                default_branch=repo.get("default_branch"),
            )
            for repo in repos
        ]
# #endregion list_gitea_repositories


# #region create_gitea_repository [C:2] [TYPE Function]
# @BRIEF Create a repository in Gitea for a saved Gitea config.
@router.post("/config/{config_id}/gitea/repos", response_model=GiteaRepoSchema)
async def create_gitea_repository(
    config_id: str,
    request: GiteaRepoCreateRequest,
    db: Session = Depends(get_db),
    _=Depends(has_permission("admin:settings", "WRITE")),
):
    _gs = get_git_service()
    with belief_scope("create_gitea_repository"):
        config = _get_git_config_or_404(db, config_id)
        if config.provider != GitProvider.GITEA:
            raise HTTPException(
                status_code=400, detail="This endpoint supports GITEA provider only"
            )
        repo = await _gs.create_gitea_repository(
            server_url=config.url,
            pat=config.pat,
            name=request.name,
            private=request.private,
            description=request.description,
            auto_init=request.auto_init,
            default_branch=request.default_branch,
        )
        return GiteaRepoSchema(
            name=repo.get("name", ""),
            full_name=repo.get("full_name", ""),
            private=bool(repo.get("private", False)),
            clone_url=repo.get("clone_url"),
            html_url=repo.get("html_url"),
            ssh_url=repo.get("ssh_url"),
            default_branch=repo.get("default_branch"),
        )
# #endregion create_gitea_repository


# #region delete_gitea_repository [C:2] [TYPE Function]
# @BRIEF Delete repository in Gitea for a saved Gitea config.
@router.delete("/config/{config_id}/gitea/repos/{owner}/{repo_name}")
async def delete_gitea_repository(
    config_id: str,
    owner: str,
    repo_name: str,
    db: Session = Depends(get_db),
    _=Depends(has_permission("admin:settings", "WRITE")),
):
    _gs = get_git_service()
    with belief_scope("delete_gitea_repository"):
        config = _get_git_config_or_404(db, config_id)
        if config.provider != GitProvider.GITEA:
            raise HTTPException(
                status_code=400, detail="This endpoint supports GITEA provider only"
            )
        await _gs.delete_gitea_repository(
            server_url=config.url,
            pat=config.pat,
            owner=owner,
            repo_name=repo_name,
        )
        return {"status": "success", "message": "Repository deleted"}
# #endregion delete_gitea_repository


# #region create_remote_repository [C:2] [TYPE Function]
# @BRIEF Create repository on remote Git server using selected provider config.
@router.post("/config/{config_id}/repositories", response_model=RemoteRepoSchema)
async def create_remote_repository(
    config_id: str,
    request: RemoteRepoCreateRequest,
    db: Session = Depends(get_db),
    _=Depends(has_permission("admin:settings", "WRITE")),
):
    _gs = get_git_service()
    with belief_scope("create_remote_repository"):
        config = _get_git_config_or_404(db, config_id)

        if config.provider == GitProvider.GITEA:
            repo = await _gs.create_gitea_repository(
                server_url=config.url,
                pat=config.pat,
                name=request.name,
                private=request.private,
                description=request.description,
                auto_init=request.auto_init,
                default_branch=request.default_branch,
            )
        elif config.provider == GitProvider.GITHUB:
            repo = await _gs.create_github_repository(
                server_url=config.url,
                pat=config.pat,
                name=request.name,
                private=request.private,
                description=request.description,
                auto_init=request.auto_init,
                default_branch=request.default_branch,
            )
        elif config.provider == GitProvider.GITLAB:
            repo = await _gs.create_gitlab_repository(
                server_url=config.url,
                pat=config.pat,
                name=request.name,
                private=request.private,
                description=request.description,
                auto_init=request.auto_init,
                default_branch=request.default_branch,
            )
        else:
            raise HTTPException(
                status_code=501,
                detail=f"Provider {config.provider} is not supported",
            )

        return RemoteRepoSchema(
            provider=config.provider,
            name=repo.get("name", ""),
            full_name=repo.get("full_name", repo.get("name", "")),
            private=bool(repo.get("private", False)),
            clone_url=repo.get("clone_url"),
            html_url=repo.get("html_url"),
            ssh_url=repo.get("ssh_url"),
            default_branch=repo.get("default_branch"),
        )
# #endregion create_remote_repository
# #endregion GitGiteaRoutes
