"""Bilgi tabanı router — panel (JWT). Thin handler'lar."""
from fastapi import APIRouter, Depends, Query

from app.auth.dependencies import get_current_tenant
from app.models.tenant import Tenant
from app.schemas.knowledge import (
    CreateFaqRequest,
    CreateManualRequest,
    CreateUrlRequest,
)
from app.services.rag.knowledge_service import KnowledgeService
from app.utils.responses import created, no_content, ok

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


@router.get("/sources")
async def list_sources(
    tenant: Tenant = Depends(get_current_tenant),
    service: KnowledgeService = Depends(),
):
    return ok(await service.list_sources(tenant.id))


@router.post("/sources/faq")
async def create_faq(
    body: CreateFaqRequest,
    tenant: Tenant = Depends(get_current_tenant),
    service: KnowledgeService = Depends(),
):
    result = await service.create_faq(tenant.id, body)
    return created(result.model_dump(mode="json"))


@router.post("/sources/manual")
async def create_manual(
    body: CreateManualRequest,
    tenant: Tenant = Depends(get_current_tenant),
    service: KnowledgeService = Depends(),
):
    result = await service.create_manual(tenant.id, body)
    return created(result.model_dump(mode="json"))


@router.post("/sources/url")
async def create_url(
    body: CreateUrlRequest,
    tenant: Tenant = Depends(get_current_tenant),
    service: KnowledgeService = Depends(),
):
    result = await service.create_url(tenant.id, body)
    return created(result.model_dump(mode="json"))


@router.delete("/sources/{source_id}")
async def delete_source(
    source_id: str,
    tenant: Tenant = Depends(get_current_tenant),
    service: KnowledgeService = Depends(),
):
    await service.delete_source(source_id, tenant.id)
    return no_content()


@router.post("/sources/{source_id}/reindex")
async def reindex_source(
    source_id: str,
    tenant: Tenant = Depends(get_current_tenant),
    service: KnowledgeService = Depends(),
):
    result = await service.reindex_source(source_id, tenant.id)
    return ok(result.model_dump(mode="json"))


@router.get("/search")
async def search_knowledge(
    q: str = Query(..., min_length=1),
    source_type: str | None = Query(default=None),
    k: int = Query(default=5, ge=1, le=20),
    tenant: Tenant = Depends(get_current_tenant),
    service: KnowledgeService = Depends(),
):
    return ok(await service.search(tenant.id, q, source_type=source_type, k=k))
