# retoor <retoor@molodetz.nl>

from typing import Any

from fastapi import Request
from fastapi.responses import JSONResponse

from devplacepy.database import get_table, resolve_by_slug
from devplacepy.responses import json_error
from devplacepy.utils import not_found
from devplacepy.services.containers import store
from devplacepy.services.containers.api import ContainerError
from devplacepy.services.audit import record as audit


def audit_instance(
    request: Request,
    user: dict,
    event_key: str,
    inst: dict,
    project: dict | None = None,
    summary: str | None = None,
    metadata: Any = None,
) -> None:
    links = [audit.instance(inst["uid"], inst.get("name"))]
    if project:
        links.append(audit.project(project["uid"], project.get("title")))
    audit.record(
        request,
        event_key,
        user=user,
        target_type="instance",
        target_uid=inst["uid"],
        target_label=inst.get("name"),
        metadata=metadata,
        summary=summary or f"{user['username']} {event_key} instance {inst.get('name')}",
        links=links,
    )


def project_for(project_slug: str) -> dict:
    project = resolve_by_slug(get_table("projects"), project_slug)
    if not project:
        raise not_found("Project not found")
    return project


def slug_of(project: dict) -> str:
    return project["slug"] or project["uid"]


def fail(exc: ContainerError) -> JSONResponse:
    return json_error(400, str(exc))


def instance_for(project: dict, uid: str) -> dict:
    inst = store.get_instance(uid)
    if not inst or inst["project_uid"] != project["uid"]:
        raise not_found("Instance not found")
    return inst
