# retoor <retoor@molodetz.nl>

import logging
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from devplacepy.database import get_table, get_deleted_media
from devplacepy.attachments import delete_attachment
from devplacepy.utils import require_admin
from devplacepy.seo import base_seo_context, site_url, website_schema
from devplacepy.responses import respond, action_result
from devplacepy.schemas import AdminMediaOut
from devplacepy.services.audit import record as audit

logger = logging.getLogger(__name__)
router = APIRouter()


@router.get("/media", response_class=HTMLResponse)
async def admin_media(request: Request, page: int = 1):
    admin = require_admin(request)
    media, pagination = get_deleted_media(page)
    base = site_url(request)
    seo_ctx = base_seo_context(
        request,
        title="Media - Admin",
        description="Restore or permanently remove soft-deleted media.",
        robots="noindex,nofollow",
        breadcrumbs=[
            {"name": "Home", "url": "/feed"},
            {"name": "Admin", "url": "/admin"},
            {"name": "Media", "url": "/admin/media"},
        ],
        schemas=[website_schema(base)],
    )
    return respond(
        request,
        "admin_media.html",
        {
            **seo_ctx,
            "request": request,
            "user": admin,
            "media": media,
            "pagination": pagination,
            "admin_section": "media",
        },
        model=AdminMediaOut,
    )


@router.post("/media/{uid}/purge")
async def admin_media_purge(request: Request, uid: str):
    admin = require_admin(request)
    att = get_table("attachments").find_one(uid=uid)
    delete_attachment(uid)
    logger.info(f"Admin {admin['username']} purged media {uid}")
    audit.record(
        request,
        "attachment.delete",
        user=admin,
        target_type="attachment",
        target_uid=uid,
        target_label=att.get("filename") if att else None,
        metadata={"purge": True},
        summary=f"admin {admin['username']} purged attachment {att.get('filename') if att else uid}",
        links=[audit.attachment_link(uid, att.get("filename") if att else None)],
    )
    return action_result(request, "/admin/media")
