"""
销售日志 API 路由 — /api/sales-logs
"""
from __future__ import annotations

import asyncio
from fastapi import APIRouter, Depends, Body
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_current_user
from app.db.database import get_db
from app.schemas.auth import CurrentUserPayload
from app.schemas.response import ok
from app.services import sales_log_service

router = APIRouter(prefix="/sales-logs", tags=["销售日志"])


@router.get("", summary="查询销售日志列表")
async def list_logs(
    page: int = 1,
    size: int = 20,
    customer_id: str | None = None,
    user_id: str | None = None,
    start_date: str | None = None,
    end_date: str | None = None,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserPayload = Depends(get_current_user),
):
    result = await sales_log_service.list_logs(
        db, current_user,
        page=page, size=size,
        customer_id=customer_id,
        user_id=user_id,
        start_date=start_date,
        end_date=end_date,
    )
    return ok(data=result)


@router.post("", summary="创建销售日志")
async def create_log(
    content: str = Body(..., embed=True),
    customer_id: str | None = Body(None, embed=True),
    contact_ids: list[str] | None = Body(None, embed=True),
    log_date: str | None = Body(None, embed=True),
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserPayload = Depends(get_current_user),
):
    from datetime import date as date_type

    parsed_date = None
    if log_date:
        parsed_date = date_type.fromisoformat(log_date)

    result = await sales_log_service.create_log(
        db, current_user,
        content=content,
        customer_id=customer_id,
        contact_ids=contact_ids,
        log_date=parsed_date,
    )

    # 异步触发 Dify 画像提取工作流（仅当关联了客户时）
    if customer_id:
        import uuid
        asyncio.create_task(
            sales_log_service.trigger_persona_workflow(
                log_id=uuid.UUID(result["id"]),
                customer_id=uuid.UUID(customer_id),
                content=content,
                salesperson_name=getattr(current_user, "real_name", ""),
                contact_ids=contact_ids,
            )
        )

    return ok(data=result, message="日志创建成功")
