"""Explicit cleanup helpers for Forgejo connection/repository deletes."""

from __future__ import annotations

from typing import TYPE_CHECKING

from sqlmodel import select

from app.models.board_repository_links import BoardRepositoryLink
from app.models.forgejo_connections import ForgejoConnection
from app.models.forgejo_issues import ForgejoIssue
from app.models.forgejo_repositories import ForgejoRepository

if TYPE_CHECKING:
    from sqlmodel.ext.asyncio.session import AsyncSession


async def delete_repository_with_dependents(
    session: AsyncSession,
    repository: ForgejoRepository,
) -> None:
    """Delete a tracked repository and rows that reference it."""
    link_statement = select(BoardRepositoryLink).where(
        BoardRepositoryLink.repository_id == repository.id,
        BoardRepositoryLink.organization_id == repository.organization_id,
    )
    links = (await session.exec(link_statement)).all()
    for link in links:
        await session.delete(link)

    issue_statement = select(ForgejoIssue).where(
        ForgejoIssue.repository_id == repository.id,
        ForgejoIssue.organization_id == repository.organization_id,
    )
    issues = (await session.exec(issue_statement)).all()
    for issue in issues:
        await session.delete(issue)

    await session.delete(repository)


async def delete_connection_with_repositories(
    session: AsyncSession,
    connection: ForgejoConnection,
) -> None:
    """Delete a Forgejo connection and all tracked repositories under it."""
    repository_statement = select(ForgejoRepository).where(
        ForgejoRepository.connection_id == connection.id,
        ForgejoRepository.organization_id == connection.organization_id,
    )
    repositories = (await session.exec(repository_statement)).all()
    for repository in repositories:
        await delete_repository_with_dependents(session, repository)

    await session.delete(connection)
