from datetime import datetime
from typing import Optional

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from tools.conversation_cleanup import (
    delete_conversation_by_chat_id,
    delete_conversations_by_time,
)


router = APIRouter(prefix="/api/admin", tags=["admin"])


class DeleteConversationByChatRequest(BaseModel):
    chat_id: str


class DeleteConversationsByTimeRequest(BaseModel):
    before: Optional[datetime] = None
    after: Optional[datetime] = None


@router.post("/conversations/delete/by-chat")
async def delete_by_chat(request: DeleteConversationByChatRequest):
    if not request.chat_id.strip():
        raise HTTPException(status_code=400, detail="chat_id is empty")
    return await delete_conversation_by_chat_id(request.chat_id)


@router.post("/conversations/delete/by-time")
async def delete_by_time(request: DeleteConversationsByTimeRequest):
    if request.before is None and request.after is None:
        raise HTTPException(status_code=400, detail="before or after is required")
    return await delete_conversations_by_time(
        before=request.before,
        after=request.after,
    )
