import { type NextRequest, NextResponse } from "next/server"
import { IngestionService, type IngestionRequest } from "@/services/IngestionService"

// POST /api/ingest - 数据接入端点
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()

    // 验证请求数据
    if (!body.source || !body.originalData) {
      return NextResponse.json({ error: "缺少必需字段: source 和 originalData" }, { status: 400 })
    }

    const ingestionRequest: IngestionRequest = {
      source: body.source,
      sourceUserId: body.sourceUserId,
      sourceRecordId: body.sourceRecordId,
      originalData: body.originalData,
      timestamp: body.timestamp || new Date().toISOString(),
    }

    const ingestionService = IngestionService.getInstance()
    const result = await ingestionService.processIngestionRequest(ingestionRequest)

    return NextResponse.json({
      success: true,
      data: {
        userId: result.userId,
        coreProfileFields: Object.keys(result.coreProfile).length,
        tagsCount: result.unifiedTags.length,
        sourceProfilesCount: result.sourceProfiles.length,
      },
      message: "数据接入成功",
    })
  } catch (error) {
    console.error("数据接入API错误:", error)
    return NextResponse.json(
      {
        error: "数据接入失败",
        details: (error as Error).message,
      },
      { status: 500 },
    )
  }
}

// POST /api/ingest/batch - 批量数据接入端点
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json()

    if (!Array.isArray(body.requests)) {
      return NextResponse.json({ error: "requests 必须是数组" }, { status: 400 })
    }

    const ingestionService = IngestionService.getInstance()
    const results = await ingestionService.processBatchIngestion(body.requests)

    return NextResponse.json({
      success: true,
      data: {
        processedCount: results.length,
        totalRequests: body.requests.length,
        results: results.map((result) => ({
          userId: result.userId,
          coreProfileFields: Object.keys(result.coreProfile).length,
          tagsCount: result.unifiedTags.length,
        })),
      },
      message: `批量处理完成，成功处理 ${results.length}/${body.requests.length} 条记录`,
    })
  } catch (error) {
    console.error("批量数据接入API错误:", error)
    return NextResponse.json(
      {
        error: "批量数据接入失败",
        details: (error as Error).message,
      },
      { status: 500 },
    )
  }
}

// GET /api/ingest/status - 获取数据接入状态
export async function GET(request: NextRequest) {
  try {
    // 模拟获取接入状态数据
    const status = {
      totalIngested: 125678,
      todayIngested: 1234,
      activeSources: 8,
      lastIngestionTime: new Date().toISOString(),
      dataQuality: 94.6,
      processingQueue: 23,
    }

    return NextResponse.json({
      success: true,
      data: status,
    })
  } catch (error) {
    console.error("获取接入状态API错误:", error)
    return NextResponse.json({ error: "获取状态失败" }, { status: 500 })
  }
}
