# retoor <retoor@molodetz.nl>

from .core import _now_iso, datetime, db, get_table, timezone
from .soft_delete import soft_delete


def record_fork(
    source_project_uid: str, forked_project_uid: str, forked_by_uid: str
) -> None:
    from devplacepy.utils import generate_uid

    get_table("project_forks").insert(
        {
            "uid": generate_uid(),
            "source_project_uid": source_project_uid,
            "forked_project_uid": forked_project_uid,
            "forked_by_uid": forked_by_uid,
            "created_at": datetime.now(timezone.utc).isoformat(),
            "deleted_at": None,
            "deleted_by": None,
        }
    )


def get_fork_parent(forked_project_uid: str) -> dict | None:
    if "project_forks" not in db.tables:
        return None
    relation = get_table("project_forks").find_one(
        forked_project_uid=forked_project_uid, deleted_at=None
    )
    if not relation:
        return None
    return get_table("projects").find_one(
        uid=relation["source_project_uid"], deleted_at=None
    )


def count_forks(source_project_uid: str) -> int:
    if "project_forks" not in db.tables:
        return 0
    return get_table("project_forks").count(
        source_project_uid=source_project_uid, deleted_at=None
    )


def soft_delete_fork_relations(project_uid: str, deleted_by: str) -> None:
    if "project_forks" not in db.tables:
        return
    stamp = _now_iso()
    soft_delete("project_forks", deleted_by, stamp=stamp, forked_project_uid=project_uid)
    soft_delete("project_forks", deleted_by, stamp=stamp, source_project_uid=project_uid)


def delete_fork_relations(project_uid: str) -> None:
    if "project_forks" not in db.tables:
        return
    forks = get_table("project_forks")
    forks.delete(forked_project_uid=project_uid)
    forks.delete(source_project_uid=project_uid)
